我写的时候:
#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;
}
我知道我们的数组之间的区别,我的是字符串数组,上面的代码是字符串,它是字符数组。但是在某些帖子中,我看到了字符数组不是以null结尾的。但也许在cs50.h中,他们将字符串实现为字符数组,并以空字符终止。我迷路了。
答案 0 :(得分:3)
string a[] = {"1","2"}
是2元素数组。不会附加任何隐藏的NULL指针。访问a[2]
(可能是它的第3个元素)会导致程序未定义。分析不同的变量如何影响行为未定义的程序并没有多大意义。随编译器的不同而不同。
#include <stdio.h>
int main(void)
{
//arrays of char initialized with a string literal end with '\0' because
//the string literal does
char const s0[] = "12";
#define NELEMS(Array) (sizeof(Array)/sizeof(*(Array)))
printf("%zd\n", NELEMS(s0)); //prints 3
//explicitly initialized char arrays don't silently append anything
char const s1[] = {'1','2'};
printf("%zd\n", NELEMS(s1)); //prints 2
//and neither do array initializations for any other type
char const* a[] = {"1","2"};
printf("%zd\n", NELEMS(a)); //prints 2
}