1

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?

aeb-dev
  • 313
  • 5
  • 16
tiwarinitin94
  • 114
  • 2
  • 13

3 Answers3

1

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.

artm
  • 17,291
  • 6
  • 38
  • 54
0

The "%s" format specifier for printf always expects a char* argument. so this is working and correct statement

printf("\n%s",stackValue);

and in first statement you are passing value so it will give you undefined behaviour.

Mohan
  • 1,871
  • 21
  • 34
0

What you are trying to do is this:

int main(void)
{
    char a_data = "Hello, this is example";
    char *pa_stack[] = {a_data};

    printf("We have: %s\n", *pa_stack);
}
aeb-dev
  • 313
  • 5
  • 16