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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

yeah it is , but my question still remains, when I use *stackValue it doesnt print the value of s[] but print an int value, and when I print 'stackValue ' only it prints the value
it doesn't matter what it prints - it's undefined behaviour (that means anything can happen). Your code is wrong from the start so there is not much point to elaborate in the wrong printf.
I have amend my code again still it not giving the right output
@NitinTiwari accepting an answer is ok, but you should vote first before accept
Sorry now I did
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);
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.