【问题标题】:Segmentation fault when trying to get a character from a string in a 2D array尝试从二维数组中的字符串中获取字符时出现分段错误
【发布时间】:2015-10-23 11:24:29
【问题描述】:

我正在尝试从二维数组中的字符串中获取字符。我目前有这个代码:

Board setData(Board b, char c, int i, int j) {
  printf("setData called\n char = %c, i = %d, j = %d\n", c, i, j);
  int index = getCharIndex(c);
  printf("Index is %d\n", index);
  char* data = b.cells[i][j];
  printf("Pre-Data = %s\n", data);
  printf("data[index] = %c\n", data[index]); // <---
  data[index] = c;
  printf("Post-Data = %s\n", data);
  b.cells[i][j] = data;
  printf("setData complete!\n");
  return b;
}

其中 Board 是一个 typedef 结构。所有打印都按预期显示值。但是,执行标记的行时会发生分段错误。从上一行我们知道 'data' 是一个字符串,那么为什么在尝试从字符串中查找一个字符时会失败呢?这不是因为 index 的值超出了字符串的范围,当字符串由多个字符组成时 index 为 0 时它会失败。非常感谢任何帮助。

编辑: 麦克维:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

typedef struct {
    char *cells[10][10];
} Board;

Board newBoard() {
  Board board;
  for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
      board.cells[i][j] = "----";
    }
  }
  return board;
}

Board setData(Board b, int index, char c, int i, int j) {
  printf("setData:\nindex = %d\nchar = %c\ni = %d\nj = %d\n", index, c, i, j);
  char* data = b.cells[i][j];
  printf("data = %s\nSetting data[%d] to %c\n", data, index, c);
  data[index] = c;
  printf("Assigning data back to b.cells[%d][%d]", i, j);
  b.cells[i][j] = data;
  return b;
}

int main(int argc, char *argv[argc]) {
  Board b = newBoard();

  int index = atoi(argv[1]);
  char c = argv[2][0];
  int i = atoi(argv[3]);
  int j = atoi(argv[4]);

  setData(b, index, c, i, j);

}

给出输出:

setData:
index = 0
char = A
i = 2
j = 2
data = ----
Setting data[0] to A
Segmentation fault

期望的结果是,在指定 i,j 处的元胞数组中的字符串中的“-”在索引位置更改为给定字符。

【问题讨论】:

  • 也许它在你分配给data[index]data 是字符串文字之后的那一行失败,这是一个只读字符串?
  • 另一种选择是 index 超出范围,您正在访问一个 nil 值。由于这个原因,我有很多段错误。
  • 请提供一个最小、完整和可验证的示例。您的问题,就其本身而言,不足以提供帮助。请参阅:stackoverflow.com/help/mcve
  • 我同意MCVE的要求,至少包括Board-&gt;cells的声明。
  • 我们需要看看Data是在哪里定义的,它的值是什么。您很可能试图访问数据的无效部分或分配错误。

标签: c arrays string


【解决方案1】:

问题是"----",作为一个字符串文字,很可能位于只读(写保护)内存块中。如果您要修改其内容,请使用例如复制strdup("----"),别忘了在某个时候释放内存。

【讨论】:

  • 谢谢你,完美地完成了这项工作:D
猜你喜欢
  • 2021-03-25
  • 2020-06-24
  • 2015-04-13
  • 2020-03-26
  • 2022-01-11
  • 1970-01-01
  • 2016-12-05
  • 2019-01-28
  • 2018-04-24
相关资源
最近更新 更多