new learner ; something puzzle about pointer;
As I learn from books, before using the pointer it must be initialized , so we usually use like this
int a = 12;
int * p = &a;
so I understand why int* p = 12
is wrong ,because it has no address;
then I find something today while coding , That is from this :
char * months[12] = {"Jan", "Feb", "Mar", "April", "May" , "Jun", "Jul"
,"Aug","Sep","Oct","Nov","Dec"};
Then another usually used situation came to my mind , That is :
char *p = "string"; (this is ok , why int * a = 12 can't be allowed ?)
I am puzzled. when is it initialized and how ? and why int * a = 12
can't be auto initialized ? maybe something about the arrange of memory.
First off:
int a = 12;
int* p = &a;
This works because &a
is a memory address.
int* p = 12;
This fails mostly because 12 is not a memory address. It's also true that 12, by itself, has no address, but this would be better reflected by a snippet like int* p = &12;
(which wouldn't work, as you correctly noted).
An interesting property of pointers is that they are often used to designate the start of a list of values. For instance, take this array of integers:
int a[] = {1, 3, 7, 13};
It can trivially be turned into an integer pointer.
int* p = a; // magic!
The pointee is the first element of a
, so *p == 1
. Now, you can also do p[0]
(which is 1, too), p[1] == 3
, p[3] == 7
, and p[4] == 13
.
The reason char* foo = "bar"
works is that "bar" is not a single value: it's a character array in disguise. Single characters are denoted by single quotes. As a matter of fact:
"bar"[0] == 'b'
"bar"[1] == 'a'
"bar"[2] == 'r'
The compiler has special support for string literals (quoted strings) that make it possible to assign them straight to pointers. For instance, char* foo = "bar"
is valid.
A C99-compliant compiler also has support for array literals. For instance, int* p = (int [3]){1, 2, 3};
is valid. The character array and the int array will be given a global address, because the people who made C felt that it was a useful thing to do.
int* p = 12
is wrong because the assigned value may or may not belongs to memory address. You are forcing p
to point at that location.char *p = "string"
is allowed because compiler already has set the space for the string and p
is pointing to the first character of that string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With