为结构数组动态分配内存 [英] Dynamically allocate memory for Array of Structs

查看:35
本文介绍了为结构数组动态分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

#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 Xcode 5.0.1 编译器.我读过很多例子,编译器似乎不同意在哪里使用 struct 标签.在 sizeof() 命令中使用 struct 引用似乎根本无法识别 struct.

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.

推荐答案

您的代码中存在一些错误.做到这一点:

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 */
}

基本上你必须使用 struct 关键字,除非你把它 typedef 去掉,并且全局变量 myBigList 有错误的类型.

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

这篇关于为结构数组动态分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆