简体   繁体   English

while循环中字符串数组末尾的分段错误

[英]Segmentation fault at the end of an array of strings in a while loop

Here's part of my code 这是我的代码的一部分

char **images; // An array of strings filled with valid data

while(*images)
{
    printf("input image = %s\n", *images);
    images++;
}

I'm expecting it to exit the loop when the end of the array is reached but it still goes inside the loop and crashes. 我期望它在到达数组末尾时退出循环,但仍会进入循环并崩溃。 Please suggest how to fix this issue. 请提出如何解决此问题的建议。 The number of elements in the array is not fixed. 数组中的元素数量不是固定的。

The code will not know how to stop since the while loop is always true, ie not zero. 代码不会知道如何停止,因为while循环始终为true,即不为零。 Even if you run past the end of the array into unmarked address space the code will keep going and then segfault as you suggest. 即使您经过数组末尾进入未标记的地址空间,代码也会继续运行,然后按照您的建议进行段错误。

You should always close off string data with a marker such as "\\0" and perform a check in the while loop ie: 您应该始终使用“ \\ 0”之类的标记关闭字符串数据,并在while循环中执行检查,即:

while ( strcmp(*images, "\0") != 0 )

or you should know the size of the **images array and stop after reading the last item. 或者您应该知道** images数组的大小,并在阅读最后一项后停下来。 For this reason its probably better to use a for loop instead of a while loop. 因此,最好使用for循环而不是while循环。 The strcmp version above is much less efficient. 上面的strcmp版本效率低得多。 The for loop should be very efficient. for循环应该非常有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM