1

I'm trying to grasp the concept of arrays of structures and came up with a problem. Hopefully you can help me out.

Okay, so, the problem I'm facing is how to declare and use (i.e. accept & display values) of an array variable within an array of structures?

This sample code may visually help you to understand my problem:

#include<stdio.h>

struct node{

    int roll;
    char name[10];
    int grades[5]; // Accepts 5 grades for each student
};

int main()
{
    struct node student[3];

    /*Accept and display values for structure members here*/

    return 0;
}

I know there's a similar example here.

But I don't understand line 4 in the accepted answer's main() section, where memory is allocated using malloc() :

list[ip].inputs[inp]= (char*)malloc(25);

I'm getting confused between the 25 bytes allocated here and the 10 defined in char* inputs[10];

What exactly is happening here? And how do you solve the problem I mentioned above?

4

3 回答 3

2

*您引用的示例中有一个额外的内容。malloc仅因为这一点才需要,在您的示例inputs中是一个包含 10 个指针的数组,char而这里name是一个保存 10 秒的缓冲区char。您的代码中不需要任何malloc内容​​。

您的结构在内存中看起来像这样(假设 4-bytes ints):

在此处输入图像描述

你的student数组main看起来像:

在此处输入图像描述

如您所见,字段是一个接一个地布置的。因此,要读取您必须写入的第一个学生的姓名student[0].name(使用strncpy以确保没有溢出)。要更改您将使用的第二个学生姓名的第三个字母student[1].name[2]

于 2013-08-11T13:55:31.483 回答
1

您可以像这样安全地使用它:

strcpy(student[1].name, "Yu Hao");
student[1].grades[1] = 95;

printf("student 1 name: %s\n", student[1].name);
printf("student1 grades1:%d\n", student[1].grades[1]);

您链接的示例使用malloc因为struct有一些指针,并且指针在使用之前必须指向有效的地方。在您的示例中并非如此。

请注意,strcpy当您复制长度超过 10 的字符串时,使用可能会导致灾难,如果需要考虑,请strncpy改用。

于 2013-08-11T13:58:13.110 回答
0

回答与推荐帖子相关的问题。

首先,希望你对C中的指针有基本的了解。指针确实是一个内存地址的简称。有关详细信息,我向您推荐这本小册子(关于数组和指针的非常出色的介绍)。在那段代码中,inputs被定义为char* inputs[10];。它是一个指针数组。所以该数组中的每个元素都应该是一个地址。25调用中的参数malloc不是必需的(您也可以指定4050满足您的要求)。您唯一应该保证的是数组中的每个元素都是一个地址(这就是malloc返回的内容)。10指定数组维度,即您可以将地址10总数存储在inputs或者说,您可以通过调用来初始化数组malloc十次像:

struct a;
for (int i = 0; i < 10; i++) {
    a.inputs[i] = (char *) malloc(25);
}

回到你自己的问题。在您的情况下,该符号name标识存储的地址。您无需 malloc 新存储。

于 2013-08-11T14:09:50.473 回答