I was studying pointers and this is what i learned:-
int a = 23;
int *ptr = &a;
char b = 'b';
char *pnt = &b;
char *str = "string";
Value assigned to a pointer is an address. So i can't do int *ptr = 7; or char *k = 'c';. But i can do char *str = "string"; because "string" is not a char but an array of some char values, as chars and pointers are quite similar to each other, So in above code if i print printf("%p", str); should print address saved in str which should be the address of starting address of string (This is the 1st part where i want to know i am right or wrong)
So in another way by doing char *str = "string"; i am just creating an array of chars like {'s','t','r','i','n','g'}. (maybe this is going to sound very stupid but that's what it is) So i thought why not try char *str = {'s','t','r','i','n','g'};, i thought that printf("%p\n", str) will again give starting address of string but after getting some weired value and running printf("%c", str) returned 's' i found it is giving the very 1st element of array instead of address. and i tried same with int array and noticed a warning saying
int *array = {1,2,3};
warning: initialization of 'int *' from ' int' makes pointer from integer without a cast
As per my understanding of this, compiler treating {1,2,3} as an int not as an array, i am not sure why but if i cast explicitly it is running fine like int *array = (int[]){1,2,3}. I am not sure why i need to tell explicitly but i think this is how compiler sees it
- after doing
int *array = {1,2,3};compiler is getting an address of {1,2,3}. - but when compiler sees there is an int at that address it is reading that int only
- and compiler sees it like
int *array = 1notint *array = {1,2,3}
i don't know if my theory is right or not. If not please i want to know why this is happening and why doing char *str = "string" doesn't need any cast.