Patrick Patrick - 2 months ago 22
C Question

How to assign string into char* pointer?

#include <stdio.h>

struct Analysis {
int lnlen;
int arr[2];
char* name;
};

int main()
{
struct Analysis ana_space[2];
char *ptr = (void*) &ana_space;

ana_space[0].lnlen = 0;
ana_space[0].arr[0] = 1;
ana_space[0].arr[1] = 2;
ana_space[0].name = "Peter";

printf("\n%d\n", *ptr); // print 0;

*ptr = 10; // how to use memcpy here;

printf("\n%d\n", *ptr); // print 10;

ptr = ptr + sizeof(int); // advance pointer by int;

printf("\n%d\n", *ptr); // print 1;

ptr = ptr + 2*sizeof(int); // advance pointer by 2 ints;

printf("\n%s\n", *ptr); // print "Peter"; --------------not work

//*ptr = "Jim"; // how to assign new name "Jim" into that memory;
return 0;
}


Output:


0

10

1

(null)


I want to use char * as pointer to go through memory address to get some data and also store value into memory.

For int and int array, it works fine, but not for the string.

How to print the string and store new string value into memory?

Answer

Your approach is not portable. It will be better to use offsetof to make sure that you can reliably point to the addresses of the members of a struct.

int main()
{
    struct Analysis ana_space[2];
    char *ptr = (void*) &ana_space;

    size_t offset1 = offsetof(struct Analysis, arr);
    size_t offset2 = offsetof(struct Analysis, name);

    ana_space[0].lnlen = 0;
    ana_space[0].arr[0] = 1;
    ana_space[0].arr[1] = 2;
    ana_space[0].name = "Peter";

    // advance pointer to point to arr.
    ptr = ptr + offset1;

    // advance pointer to point to name
    ptr = ptr + (offset2-offset1);

    // Cast the pointer appropriately before dereferencing.
    printf("\n%s\n", *(char**)ptr); 

    // how to assign new name "Jim" into that memory;
    *(char**)ptr = "Jim";
    printf("\n%s\n", *(char**)ptr);

    return 0;
}

Your use of:

printf("\n%d\n", *ptr);     // print 0;

*ptr = 10;                  // how to use memcpy here;

printf("\n%d\n", *ptr);     // print 10;

and the expected output is flawed. It works only with little endian systems. I suggest using:

printf("\n%d\n", *(int*)ptr);

*(int*)ptr = 10;

printf("\n%d\n", *(int*)ptr);