简体   繁体   English

C-为什么我在尝试读取包含反斜杠的字符时遇到段错误?

[英]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.

相关问题 我在尝试打开文件并将其写入另一个文件时遇到段错误 - I'm getting a segfault trying to open a file and write it to another 为什么在 C 中修改了字符串,即使我没有尝试修改它? - Why is string modified in C even when I'm not trying to modify it? 在C中打印数组时为什么会出现分段错误? - Why I'm getting segmentation fault when I'm printing array in C? 不知道为什么我要为char数组中的第一个元素获取此输出 - Not sure why I'm getting this output for first element in char array 尝试递归浏览C中的目录时,为什么会出现段错误? - Why am I getting a segfault, when trying to recursively navigate directories in C? 我正在尝试将文件读入数组并不断收到此错误 - I'm trying to read a file into an arrray and keep getting this error 为什么在重新分配空间后将 char 分配给指向指针 char 的指针时会出现段错误? - Why am I getting a segfault when assign a char to a pointer to pointer char after realloc space for it? 我遇到了段错误,但似乎找不到 - I'm getting a segfault and can't seem to find it 我正在尝试从文件中仅读取前3个字符-c - I'm trying to read only the first 3 chars from a file - c 为什么我对未分配的内存有读写权限? - Why I'm getting read and write permission on unallocated memory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM