Home > Blockchain >  How do I get string from the address of char*?
How do I get string from the address of char*?

Time:10-13

char *p = "cat";
char a = *p;
printf("%c", &a);

The code above doesn't working. How do I get string data "cat" from pointer *p and store it at char a? Statement 'char *p = "cat";' should not be changed.

CodePudding user response:

The pointer p in your code points to the first value of the string which is c. So when you assign the value at p to a you will get the character ‘c’ stored in a. But then you in the last line of your code you wrote &a which refers to the address of a which will be a garbage value and won’t give any results. Alternatively if you would have written *p or a instead of &a you would have gotten ‘c’ as the result.

CodePudding user response:

As above: A char can store only one character. A string is an array of characters ending with '\0'. So loop through the string and recover the characters until the termination '\0' is found.

#include <stdio.h>

int main ()
{
    char *p = "cat";

    int i = 0; char a[100];

    while (*p != '\0')
    {
        a[i] = *p;
        i   ; 
        p  = 1;
    }
    a[i] = '\0';

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

    return 0;
}

The output is: cat

  • Related