【发布时间】:2019-11-12 21:10:11
【问题描述】:
我创建了一个简单的程序,它有一个结构node,它只包含一个int id。在main() 中,我创建了一个节点指针array,并使用malloc(sizeof(struct node)*3) 为三个struct node 分配空间。然后我让这三个指针指向节点first、second 和third。
但是,我还创建了一个fourth 和fifth 节点,并将它们分配给第三个节点之后的指针。我原以为会出现分段错误,但程序却成功读取并打印了 fourth 和 fifth 的 int id,尽管事实上我没有分配内存。
我误会malloc()了吗?另外,如果我们将指针视为数组,有没有办法获取该数组中元素的数量?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
struct node{
int id;
};
int main(){
struct node * array;
array = malloc(sizeof(struct node) * 3);
struct node first = {7};
struct node second = {8};
struct node third = {9};
struct node fourth = {10};
struct node fifth = {11};
*(array + 0) = first;
*(array + 1) = second;
*(array + 2) = third;
*(array + 3) = fourth;
*(array + 4) = fifth;
printf("%d, %d, %d, %d, %d\n", (array + 0) -> id, (array + 1) -> id, (array + 2) -> id, (array + 3) -> id, (array + 4) -> id);
printf("%d\n", sizeof(array));
}
【问题讨论】: