数组C的动态内存分配

时间:2016-04-06 20:50:43

标签: c arrays pointers

所以今天在大学我们有这个简单的程序,我们必须输入n个学生的高度,然后打印出高度的总和。高度存储在一个数组中。现在这很简单 - 然而,我们用固定数量的学生开始了问题,在我的例子中有5个。然后我问教授,如果学生人数尚未定义,我将如何解决问题,她告诉我必须使用列表和动态数组元素分配。我们还没到达那个,所以我来这里寻求帮助,因为我有兴趣像那样解决它。

有人可以展示/解释或给我一些关于如何处理问题的指导。以下是课堂上问题的解决方法。

#include <stdio.h>
#include <conio.h>

int main(){


    int height[5], sum=0, i;
    int numOfStudents=5;
    float average;

    for(i=0; i<numOfStudents; i++){  
        printf("Type in the height of the %d. student: ", i+1);
        scanf("%d", &height[i]);

        sum+=height[i];
    }
    printf("\n Sum of all heights is: %d. There were %d students", sum, numOfStudents);

return 0;   
}

2 个答案:

答案 0 :(得分:1)

只需将height定义为指针

即可

int *height;

然后分配dinamically内存来存储数组元素

height = malloc( sizeof(int) * numOfStudents );

请注意,适当的大小(以字节为单位)计算为int大小与数组项数量的乘积。

这种方法意味着预先知道数组的大小。

由于记忆是以动态方式分配的,因此你有责任通过

来释放它

free(height);

因为你不再需要这个数组了。

整个事情变成

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

int main()
{
    int *height, sum=0, i;
    int numOfStudents=5;

    height = malloc( sizeof(int) * numOfStudents );

    for(i=0; i<numOfStudents; i++)
    {
        printf("Type in the height of the %d. student: ", i+1);
        scanf("%d", &height[i]);

        sum+=height[i];
    }

    printf("\n Sum of all heights is: %d. There were %d students", sum, numOfStudents);

    free( height );

    return 0;   
}

答案 1 :(得分:1)

首先,您需要了解'list'是一种抽象数据类型,如下所示: https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Singly_linked_list.png/220px-Singly_linked_list.png

它包含许多像链一样相互连接的节点,每个节点都有自己的值。

用c语言实现这种数据结构的简便方法如下:

struct Node {
    int val;
    struct Node* next;
};

'val'存储值,'next'将地址存储到下一个节点。将'struct Node *'视为一个整体,您将学习代表'struct Node pointer',它精确地指向一个节点的地址。

现在你可以创建一个包含2个元素的列表:

struct Node* n1 = malloc(sizeof(struct Node));
n1->val = 200;
struct Node* n2 = malloc(sizeof(struct Node));
n2->val = 300;
n1->next = n2;

保持附加元素,您可以创建一个列表'节点',无论你想要什么长度。

相关问题