我已经定义了一个结构,
struct RadBuck {
int size,
int pos,
int head
};我想以RadBuck *R[n]的形式创建这个结构的数组。如果n是小的,那么一切都很好,但是当我达到9MB时,就会出现分段错误。我对int a[n]也有同样的问题,但是我克服了,通过malloc实现了int *a = (int*) malloc(n*sizeof(int));,因为这对于struct来说是不可能的,我很困惑。
发布于 2014-02-25 18:05:14
因为这是不可能的结构,我很困惑。
当然,是可能的:
#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;
};使用分号(;)分隔结构的成员声明。
发布于 2014-02-25 18:51:54
当您使用malloc或声明一个大小为n的数组时,编译器尝试将所需的空间分配为内存中的连续空间。因此,如果您需要大量内存,您应该尝试使用链接列表而不是向量。当您使用链接列表时,您的元素在内存中是稀疏的,您应该会得到更多。如果要使用链接列表,可以这样重写结构:
struct RadBuck {
int size;
int pos;
int head;
struct RadBuck *next;
};https://stackoverflow.com/questions/22022323
复制相似问题