我定义了一个结构,
struct RadBuck {
int size,
int pos,
int head
};
我想创建一个这种结构的数组作为 RadBuck *R[n]
。如果 n
很小,一切都很好,但当我达到 9 MB 时,出现段错误。我对 int a[n]
也有同样的问题,但是我通过 malloc
克服了这个问题, int *a = (int*) malloc (n*sizeof(int));
由于这对于 struct 是不可能的,所以我很困惑。
最佳答案
Since that is not possible for struct, I am confused.
这肯定是可能的:
#include <stdlib.h> /* for malloc() */
#include <stdio.h> /* for perror() */
size_t n = 42;
struct RadBuck * p = malloc(n * sizeof(*p)); /* Here one also could do sizeof(struct RadBuck). */
if (NULL == p)
{
perror("malloc() failed");
}
else
{
/* Use p here as if it were an array. */
p[0].size = 1; /* Access the 1st element via index. */
(p + n - 1)->size = 2; /* Access the last element via the -> operator. */
}
free(p); /* Return the memory. */
顺便说一句,应该是:
struct RadBuck {
int size;
int pos;
int head;
};
使用分号 (;
) 分隔结构的成员声明。
关于c - 在c中分配大型指针数组(9mb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022323/