简体   繁体   中英

assign and allocate memory for a pointer inside a struct in C?

Suppose I have a struct:

struct b {
    unsigned short  num;
    unsigned short  size;
    unsigned char  *a;
};

I then declare a pointer that points to a struct of b :

struct b *foo=malloc(sizeof(struct b));

how do I allocate memory for foo 's a and assign a to point to a character string?

It's not that different, eg, to allocate the memory for the string hello :

char *hello = "hello";
foo->a = malloc(strlen(hello) + 1);
strcpy(foo->a, hello);

Actually, struct b *foo = malloc(sizeof *foo); already allocates enough space to accomodate a char pointer, so it depends on what you want to do with foo->a (ps: because foo is a pointer, you need to use the indirection operator).

If foo->a (or, *(foo).a ) can be a constant string, you can simply do this:

struct b *foo = malloc(sizeof *foo);
foo->a = "A constant string";

Note that, because this is (sort of) equivalent to:

const char *const_str = "this is read-only";

You can't change anything about the chars a points to. The member a is assigned an address of a string constant in read-only memory. In short:

foo->a = "constant";
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//prints cnt 
foo->a[0] = 'C';//WRONG!

If you want to be able to change the string, use this:

foo->a = malloc(50 * sizeof *(foo->a)));

The sizeof is optional here, since the size of char is guaranteed to be size 1, always.
To assign/copy a string you use strcat , strcpy , memcpy , strncat , sprintf and the like

strcpy(foo->a, "constant");
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//still prints cnt 
foo->a[0] = 'r';
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//still prints rnt 

Now you can change the string a points to, but as a result, you'll have to free this memory, too, when you're done with it:

//wrong:
free(foo);//works, but won't free the memory allocated for foo->a
//better:
free(foo->a);
free(foo);

应该使用'foo-> a'(运算符->)

First you have to assign memory for foo by malloc, then it will contain the address of the inside pointer called "a". When you have the memory address of "a" (not the "pointed to" but the address where the pointed to address is stored), you can store addresses there.

so: 1. struct b *foo = malloc(...) 2. foo->a = malloc(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM