# Pointer Initialization

• 11-14-2012
johan.g1
Pointer Initialization
I was having a lecture about pointers and I thought I understood already. Until I tried this simple code that doesn't work. It gives "Segmentation fault: 11".
Code:

```#include<stdio.h> int main() {   int *a;     scanf("%d", a);     printf("%d", *a);     return 0; }```
This is my understanding: in the initialization int *a, I set a to be an address pointing to an integer. Then I scan an integer and store it on the address of a. Finally I print the integer stored in the address of a. So, what went wrong?
• 11-14-2012
Click_here
Quote:

Originally Posted by johan.g1
I was having a lecture about pointers and I thought I understood already. Until I tried this simple code that doesn't work. It gives "Segmentation fault: 11".
Code:

```#include<stdio.h> int main() {   int *a;     scanf("%d", a);     printf("%d", *a);     return 0; }```
This is my understanding: in the initialization int *a, I set a to be an address pointing to an integer. Then I scan an integer and store it on the address of a. Finally I print the integer stored in the address of a. So, what went wrong?

'a' is a pointer, but it doesn't point to anywhere yet

Give it somewhere to point to first
Code:

```#include<stdio.h> int main() {     int b;     int *a;     a = &b;     scanf("%d", a);     printf("%d", *a);     return 0; }```
• 11-14-2012
Khaltazar
A better example would be the following:

By better I am not saying better than Click_here's example, I am referring to the original poster's example.

Code:

```#include <stdio.h> int main(){     int a = 0;     int * b = &a;     *b = 5;     printf("%d", a);     return 0; }```
This uses pointers to change the variable 'a' to 5 without directly using it.
• 11-14-2012
whiteflags
Quote:

Originally Posted by Khaltazar
A better example would be the following:
This uses pointers to change the variable 'a' to 5 without directly using it.

Aside from a and b being renamed, Click_here's didn't directly use the pointee either. The pointee being the thing that a pointer points to, I mean.
• 11-14-2012
Khaltazar
Quote:

Originally Posted by whiteflags
Aside from a and b being renamed, Click_here's didn't directly use the pointee either. The pointee being the thing that a pointer points to, I mean.

I didn't mean it was better than the poster above me, I was replying to the original poster. I usually don't use quotes unless I am replying to someone other than the original poster.
• 11-14-2012
Click_here
My code was not an example - It was just a slight change to the OP's code to make it work.
• 11-14-2012
johan.g1
Thanks. I think I got it now. :D