【问题标题】:argc, argv causes strange behavior in Null terminator in Cargc, argv 在 C 中的 Null 终止符中导致奇怪的行为
【发布时间】: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 才有意义
  • 在试验函数变量astringarray。你为什么要把它和一个角色比较?
  • 您将指针数组(指向字符串)中的最后一个指针与字符数组中的最后一个字符混淆了。
  • @scipsycho 我是 C 新手,这种比较可能是错误的,但我认为这不会成为问题,因为我正在比较它是否为 null,我认为是所有类型的数组都一样。

标签: c cs50


【解决方案1】:

string a[] = {"1","2"} 是一个 2 元素数组。不会有隐藏的 NULL 指针附加到它上面。访问a[2](可能是它的第三个元素)会使您的程序未定义。分析不同变量如何影响行为未定义的程序并没有多大意义。它可能因编译器而异。

#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
}

【讨论】:

  • cs50.h的源代码有“typedef char *string;”所以这有帮助。你的文字是正确的(没有检查代码)
  • @Marichyasana 我不常这么说,但在这种情况下,我相当确定我的代码也是正确的 :)
  • 我也是——无意冒犯——我只是懒惰。给你 +1
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 2016-01-25
  • 1970-01-01
  • 2015-08-09
  • 2020-10-12
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
相关资源
最近更新 更多