Nitin Tiwari Nitin Tiwari - 10 days ago 6
C Question

working with char pointer and integer pointer

My question is about dereferencing a char pointer

Here is my code -

#define MAX 10

char s[80]="Hello";

int main(){

char *stackValue;

stackValue=&s;//here I assined the address of s to stackValue

if(!stackValue){

printf("No place for Value");

exit(1);

}

else{

printf("\n%s",*stackValue);//This doesn't work with * before it

printf("\n%s",stackValue);//This works properly
}
return 0;
}


In the above code I have assigned the address of S[] to stackValue and when I am printing *stackValue it doesn't work ,

But If I print only 'stackValue' That works.

When I do same thing with Integer

int main(){
int i=10, *a;
a=&i;
printf("%d",*a);//this gives the value
printf("%d",a)//this gives the address
return 0;
}


Is printing char pointer and integer pointer is different. When I use * in int value it gives the value but gives an error when I use it as a char pointer.

Help me out?

Answer

With the first code snippet:

stackValue=&s; is incorrect given s is already an array to char. If you write like that then stackValue becomes pointer to pointer to char (not pointer to char).

Fix that by changing to stackValue=s;

Also, again %s expect a pointer to char (NOT pointer to pointer to char) - that explains why this doesn't work printf("\n%s",*stackValue); // this doesn't work

You need printf("\n%s",stackValue); instead.


With the second code snippet.

a=&i; is ok because i is a single int, NOT an array.