Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

c - Dynamically allocate memory for Array of Structs

Here's what I'm trying to do:

#include <stdio.h>
#include <stdlib.h>

struct myStruct {
    int myVar;
}

struct myStruct myBigList = null;

void defineMyList(struct myStruct *myArray)
{
     myStruct *myArray = malloc(10 * sizeof(myStruct));

     *myArray[0] = '42';
}

int main()
{
     defineMyList(&myBigList);
}

I'm writing a simple C program to accomplish this. I'm using the GNU99 Xcode 5.0.1 compiler. I've read many examples, and the compiler seems to disagree about where to use the struct tag. Using a struct reference inside the sizeof() command doesn't seem to recognize the struct at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a few errors in your code. Make it:

struct myStruct *myBigList = NULL; /* Pointer, and upper-case NULL in C. */

/* Must accept pointer to pointer to change caller's variable. */
void defineMyList(struct myStruct **myArray)
{
     /* Avoid repeating the type name in sizeof. */
     *myArray = malloc(10 * sizeof **myArray);

     /* Access was wrong, must use member name inside structure. */
     (*myArray)[0].myVar = 42;
}

int main()
{
     defineMyList(&myBigList);
     return 0; /* added missing return */
}

Basically you must use the struct keyword unless you typedef it away, and the global variable myBigList had the wrong type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...