So i was playing with pointers to understand different use cases, I'm not so experienced at this and unable to wrap my head around some ideas. I'll mark the lines where i have a problem. Please help me understand pointers.
on line 6:
Why can't I refer a string as an array, since that's how it's stored in memory i think. How to access individual characters of a string?
on line 7-8:
why is there a difference of 8 bytes between &str
and &str + 1
when int
datatype takes 4-bytes
on line 9,10 and 12:
Why does using *str
to refer to the string take int
as input?
and why does it cast a single byte char
to int
instead of casting 4 bytes?
char *str = "Ninechars";
printf("Start\n");
printf("%s\n", str);
printf("%p\n", str); // address of first char of str
printf("%p\n", str+1); // address of second char of str
// printf("%s\n", str[1]); // [segfault] warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [TODO]
printf("%p\n", &str); // address to head of the string? NO, address of the pointer var str
printf("%p\n", &str+1); // [TODO], difference of 8bytes b/w this and previous address value? [WHY]?
printf("%d\n", *str); // what integer is this? -> whatever can be made from 'N'=78
printf("%d\n", *(str+1)); // 'i'=105, but why is it taking single byte ints [TODO]
printf("%ld\n", sizeof(1)); // 4 bytes, as expected
// printf("%s\n", *str); // [?]Wrong, [HOW][WHY], format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’[TODO]
printf("End\n");
Output: Start Ninechars 0x40088f 0x400890 0x7fff95a594e8 0x7fff95a594f0 78 105 4 End
The full code file is here: http://ideone.com/ryag80