简体   繁体   中英

why does NULL condition terminate after 3 chars

I wrote this function which is supposed to read a string into an array up to the NULL char which represents the end of the string in the line. But it somehow doesn't quite work.

int main(void){
    int MAX = 39;
    char number1[MAX + 1];
    int i;

    read_array(number1, MAX);

    for(i = 0; i <= MAX; i++)
        printf("%c", number1[i]);

    return 0;
}

int read_array(char* number, int size) {
    printf("\nEnter an integer number at a maximum of 39 digits please.\n");

    int result = 0;
    char* i;
    for (i = number; *i != NULL; i++)
        scanf("%c", i);

    return result;
}

No matter how many chars I type, as I print the result it just gives me the first 3 chars and I don't understand why. Any idea? THX

As I said earlier, scanf doesn't null-terminate your strings for you. If you want to read until the user hits enter/return, check for that. You can do that by replacing your for-loop with this do-while-loop:

do {
    scanf("%c", i); // read the data into i *before* the loop condition check
} while (*i++ != '\n'); // check for '\n' (unless you expect the user to
                        // actually type the null character)

@NedStark point about i pointing to junk memory is correct. The data in number1 is never initialized, so it's just filled with junk. Your loop condition ( *i != NULL ) is checked before the scanf call, which means the loop condition is just checking old, junk data (and not the correct value).

The problem is in your loop

for (i = number; *i != NULL; i++)
    scanf("%c", i);

After incrementing i, i points to the next memory location which contains garbage data because it hasn't been properly initialized. Probably you want to something like:

char c;
i = number;
do
{
    scanf("%c", &c);
    *i = c;
    ++i;
} while (c!='\n')
*i = '\0';

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