无法访问数组指针 C 的索引

标签 c pointers

我正在尝试在 C: 中设置一个相邻的列表数组

mygraph->table = (Node *)malloc(MaxSize * sizeof(Node));
check(mygraph->table, error);
int i;
for(i = 1; i <= MaxSize; i++)
{
    mygraph->table[i].name = NULL;
    mygraph->table[i].outlist = NULL;
    mygraph->table[i].outdegree = 0;
}
...

当我运行这段代码时,它运行良好。但是当我尝试访问表中的索引时,出现段错误:

mygraph->table[n].name = name;

我检查了 n 索引,它是正确的。 MaxSize 为 10,但即使 n = 1,我也会遇到段错误。

编辑:

typedef struct linkedlist { // linked list of ints (for use in Node)
  int index;
  struct linkedlist *next;
} List;

typedef struct { // a Node of a Graph
  char *name;
  List *outlist; // adjacency list
  int outdegree; // length of outlist
  //double pagerank_score; //not needed for this exercise
} Node;

typedef struct {
  // your code goes here
  int MaxSize;      /*Maximum number of vertices that the graph can constain*/
  Node *table;     /*Adjacency lists' array*/
} Graph;

最佳答案

I get a segmentation fault even when n = 1.

这是因为您的代码有未定义的行为。它写入数组的末尾:

for(i = 1; i <= MaxSize; i++) // should be i=0 ; i<MaxSize

n10 时,代码不会在您的系统上崩溃 - 可能是因为 malloc 在 block 的末尾添加了足够的填充以容纳一个超出数组末尾的额外元素,但错误仍然存​​在。

您可以使用内存分析器找到此类隐藏的错误,例如valgrind .

解决方法是在初始化时使用正确的索引:

for(int i = 0 ; i != MaxSize ; i++) {
}

关于无法访问数组指针 C 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675922/

相关文章:

c - 零长度数组的结构填充

c++ - 在 C 中将字符串作为参数传递

c - 用指向数组的指针填充数组

c++ - 更改 syslog 日志路径

c - 循环查找不重复的数字

c - 就 cpu 而言,coSTLy 如何成为低争用互斥体

c - 使用具有相邻内存的指针定义二维数组

c - 在 C : Is void* a type?

c - 尝试从结构中检索 U32 时程序崩溃

c - 如何取消注册(编译器)和解释器循环?