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

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

问题描述

下面就是我想要做的:

#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.

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

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