以下代码运行良好:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node{
int a, b, c, d, e;
};
struct node *ptr = NULL;
printf("Size of pointer ptr is %lu bytes\n",sizeof (ptr));
printf("Size of struct node is %lu bytes\n",sizeof (struct node));
ptr = (struct node*)malloc(sizeof (ptr)); //Line 1
// ptr = (struct node*)malloc(sizeof (struct node)); //Line 2
ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;
printf("a: %d, b: %d, c: %d, d: %d, e: %d\n",
ptr->a,ptr->b,ptr->c,ptr->d,ptr->e);
return 0;
}
当编译为:
gcc -Wall file.c
我的问题是:为什么这样没问题?
malloc
函数根据参数所指定的字节数分配内存空间,这里在我使用的64位Linux机器上,sizeof ptr
是8个字节。我认为 malloc
只会提供8个字节,但它又如何访问所有的变量a、b、c、d、e呢?是只有GCC才可以还是我对标准C理解有误?据我所知,“Line 2”应该替换“Line 1”,但两行都可以正常工作。为什么呢?
int* x = (int*)rand(); *x = 123;
,但这并不意味着这是一个好主意。 - John Ledbetter