[英]C - Why I'm getting a segfault when I'm trying to read a char what contains backslash?
I'm trying to read a file line by line and my code looking for backslashes, but when it finds one, it exits with segfault. 我正在尝试逐行读取文件,并且我的代码正在寻找反斜杠,但是当找到一个反斜杠时,它将以segfault退出。 I'm using gcc on Ubuntu linux 19.04 and C11.
我在Ubuntu linux 19.04和C11上使用gcc。
void test(char **array) {
boolean a = *array[0] == '\\';
boolean b = *array[2] == '\\';
boolean c = *array[1] == '\\'; //I get segfault here.
}
int main() {
FILE *messages = fopen("messages.json", "r");
char *array = NULL;
size_t size;
getline(&array, &size, messages);
test(&array); //array contains "{\n" string here.
}
You're treating array
as if it points directly to an array, which it doesn't. 您正在将
array
视为直接指向数组,而不是指向数组。 It points to a pointer which points to an array. 它指向一个指向数组的指针。 You can fix it by changing
*array[i]
to (*array)[i]
: 您可以通过将
*array[i]
更改为(*array)[i]
:
void test(char **array) {
boolean a = (*array)[0] == '\\';
boolean b = (*array)[2] == '\\';
boolean c = (*array)[1] == '\\';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.