[英]Segmentation fault when trying to get a character from a string in a 2D array
I'm trying to get a character from a string in a 2D array. 我正在尝试从2D数组中的字符串获取字符。 I currently have this code: 我目前有以下代码:
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;
}
where Board is a typedef struct. 其中Board是一个typedef结构。 All of the prints show the values as expected. 所有印刷品均显示预期值。 However, a segmentation fault occurs when the marked line is executed. 但是,执行标记行时会发生分段错误。 We know from the previous line that 'data' is a string, so why when trying to find a character from the string does it fail? 从上一行我们知道'data'是一个字符串,那么为什么在尝试从字符串中查找字符时会失败? This isn't because the value of index is outside the range of the string, it fails when index is 0 when the string consists of multiple characters. 这不是因为index的值超出字符串的范围,当字符串由多个字符组成时,如果index为0,它将失败。 Any help is very much appreciated. 很感谢任何形式的帮助。
EDIT: mcve: 编辑: mcve:
#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);
}
which gives the output: 它给出了输出:
setData:
index = 0
char = A
i = 2
j = 2
data = ----
Setting data[0] to A
Segmentation fault
The desired result is that the '-' in the string within the cell array at the specified i,j gets changed at the index place to the given character. 理想的结果是,在指定i,j的单元格数组中的字符串中的“-”在索引位置更改为给定字符。
The issue is that "----"
, being a string literal, is most probably located in read-only (write-protected) memory block. 问题是作为字符串文字的"----"
很可能位于只读(写保护)内存块中。 If you're going to modify its contents, do the copy with eg strdup("----")
instead, and don't forget to free the memory at some point. 如果要修改其内容,请使用例如strdup("----")
进行复制,并且不要忘记在某个时候释放内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.