【发布时间】:2019-04-08 18:24:25
【问题描述】:
当我写的时候:
#include <cs50.h> // includes type string
#include <stdio.h>
void trial(string a[])
{
if(a[2] == '\0')
{
printf("Null\n");
}
}
int main(int argc, string argv[])
{
string a[] = {"1","2"};
trial(a);
}
似乎字符串数组不以 Null 字符结尾。
但是当我写 int main(void) 时,它会打印“Null”。
更奇怪的是,当我添加 return 0;到 int main(void) ,它不会打印“Null”。
我不明白发生了什么,在下面的 cs50 讲座代码中:
#include <stdio.h>
#include <cs50.h>
int len(string s)
{
int count=0;
while(s[count] != '\0')
{
count++;
}
return count;
}
int main(int argc, string argv[])
{
string s = get_string("Input: \n");
printf("Length of the string: %d \n",len(s));
return 0;
}
我知道我们的数组之间的区别,我的是字符串数组,上面的代码是字符串,它是字符数组。但是在一些帖子中,我看到字符数组不是以空值结尾的。但也许在 cs50.h 中,他们将字符串实现为以空字符结尾的字符数组。我迷路了。
【问题讨论】:
-
但是当我写 int main(void) 时,它会打印“Null”。你是什么意思?
-
可能有点难以确切知道发生了什么,因为“字符串”不是标准 C,但作为猜测,如果您正在阅读索引 [2 ] 的大小为 2 的数组,因为只有索引 0 和 1 才有意义
-
在试验函数变量
a是string的array。你为什么要把它和一个角色比较? -
您将指针数组(指向字符串)中的最后一个指针与字符数组中的最后一个字符混淆了。
-
@scipsycho 我是 C 新手,这种比较可能是错误的,但我认为这不会成为问题,因为我正在比较它是否为 null,我认为是所有类型的数组都一样。