简体   繁体   中英

argc, argv causes strange behavior in Null terminator in C

when I write:

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

It appears that array of strings does not end with a Null character.

But when I write int main(void), it prints "Null".

Even more strange , when I add return 0; to int main(void) , it does not print "Null".

I don't understand what is happening, in the cs50's lecture code that is below worked :

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

I am aware of the difference between our arrays, mine is array of strings, code above is string which is array of characters. But in some posts I saw that character arrays are not null terminated. But maybe in cs50.h they implemented a string as a array of characters that is terminated with a null character. I am lost.

string a[] = {"1","2"} is a 2-element array. There will be no hidden NULL-pointer appended to it. Accessing a[2] (the would-be 3-rd element of it) renders your program undefined. There's not much of a point in analyzing how different variables affect a program whose behavior is undefined. It can vary from compiler to compiler.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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