C语言 如何检查C中的空数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13869656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:44:08  来源:igfitidea点击:

How to check if empty array in C

carrays

提问by user1893187

I have the following code in C:

我在 C 中有以下代码:

int i = 0;
char delims[] = " \n";
char *result = NULL;
char * results[10];
result = strtok( cmdStr, delims );
while( result != NULL )
{
     results[i] = result;
     i++;
     result = strtok(NULL, " \n");
}

if(!results[1])
{
    printf("Please insert the second parameter...\n");
}
else
{
    ...
}

It always executes the elsecondition even if the results[1]is empty.

else即使results[1]为空,它也始终执行条件。

I've tried with results[1] == NULLbut no success.

我试过results[1] == NULL但没有成功。

How do I can check if it is empty or not?

我如何检查它是否为空?

回答by hmjd

Initialize the resultsarray so all elements are NULL:

初始化results数组,使所有元素为NULL

char* results[10] = { NULL };

In the posted code the elements are unitialized and will be holding random values.

在发布的代码中,元素被单元化并且将保存随机值。

Additionally, prevent going beyond the bounds of the resultsarray:

此外,防止超出results数组的边界:

while (i < 10 && result)
{
}

回答by AnT

There's no such thing as an "empty array" or an "empty element" in C. The array always holds a fixed pre-determined number of elements and each element always holds some value.

C 中没有“空数组”或“空元素”这样的东西。数组总是包含固定的预先确定数量的元素,并且每个元素总是包含一些值。

The only way to introduce the concept of an "empty" element is to implement it yourself. You have to decide which element value will be reservedto be used as "empty value". Then you'll have to initialize your array elements with this value. Later you will compare the elements against that "empty" value to see whether they are... well, empty.

引入“空”元素概念的唯一方法是自己实现它。您必须决定将保留哪个元素值用作“空值”。然后你必须用这个值初始化你的数组元素。稍后您会将元素与“空”值进行比较,以查看它们是否……好吧,空。

In your case the array in question consist of pointers. In this case selecting the null pointer value as the reserved value designating an "empty" element is an obvious good choice. Declare your results array as

在您的情况下,有问题的数组由指针组成。在这种情况下,选择空指针值作为指定“空”元素的保留值显然是一个不错的选择。将您的结果数组声明为

char * results[10] = { 0 }; // or `= { NULL };`

an later check the elements as

稍后检查元素为

if (results[i] == NULL) // or `if (!results[i])`
  /* Empty element */