One thing that always confused me , the character pointer. It's after long four years that I am again lingering into c.
Take for example the mentioned case .Why does char
pointer behave in this way ? How can we directly address the contents of the pointee when it points to nothing or is it like char pointer stores stuffs other than addresses !
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* charPtr="I cant understand why";
int* intPtr=60;
printf("%d\n", intPtr); //displays 60
printf("%p\n", intPtr); // displays the hex value of 60
printf("%s\n", charPtr); // displays the wh0le string
printf("%p\n", charPtr); // displays the start address of the string
return 0;
}
Next the int
pointer , How can it accept the value 60 and where does it get stored ?
leaving aside the char pointer and malloc ,I thought the basic idea of the pointer was to get an address to point to !
why does these cases
*intptr = 60 ; // should be setting the pointee's value to 60
intptr = 60 ; // sets the address
throw compilation error while
int* intPtr=60;
sneaked in without getting an address ( or is 60 taken as the address ,if so why is this not acceptable not in the former case)of the the pointee !
I guess I am missing something here but hey ! Guess what ? they told me to search in SO !
EDIT : Giving the address pointed to by the char pointer to an int pointer also throws in no error !
int8_t* intPtr= (int8_t*)0x80485c8 ; // works without casting too ! I guess addresses are acceptable.
Dereferencing it will give a value equivalent to the first I
of the string .Is this a good practise or there exists any other explanation to this leaving out thier byte bit size allocation such as an int can hold a char and so.. ?
As hmjd pointed out the ' initialisation syntax ' is the problem ! I have no problem writing my own code but trouble arises when modifying someone's code !