动态分配内存结构的数组
问题描述:
下面就是我想要做的:
#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);
}
我正在写一个简单的C程序来实现。我使用的是GNU99 X $ C $Ç5.0.1编译器。我看过很多例子,编译器似乎不同意在哪里使用结构
标记。使用中的的sizeof()
命令似乎并没有认识到结构一个
可言。 结构
参考
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.
答
有在code的几个误区。让它:
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 */
}
基本上,你必须使用结构
关键字,除非你的typedef
它拿走,并设置全局变量 myBigList
有错误的类型。
Basically you must use the struct
keyword unless you typedef
it away, and the global variable myBigList
had the wrong type.