c - 在c中分配大型指针数组(9mb)

标签 c arrays pointers

我定义了一个结构,

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/

相关文章:

c++ - 这与字节序有什么关系吗?

javascript - 将标记从数组添加到带有图层支持的传单中的标记簇中

arrays - Ruby 将修改后的数组保存在变量中而不更改原始数组

c - --*--指针操作?

c - 将文件写入缓冲区

c++ - 为什么这两个值在arduino上不相等?

python - 按升序对 numpy 矩阵行值进行排序

c - 该程序缺少/需要修复什么?

Java - foo.charAt(i) 的返回值如何作为引用?

c - 如何再次正确地重新分配一个 free() 的结构?