Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c - Difference between scanf for char * and char [ ]?

I'm a newbie to c programming. I'm trying to input two strings using scanf. My first try was as below

#include <stdio.h>
int main(void)
{
    char *word1;
    char *word2;
    scanf("%s", word1);
    scanf("%s", word2);
    printf("%s
", word1);
    printf("%s
", word2);
}

If I run this code, only the first input is correctly stored (word2 is null). But, if I run the code below, both inputs are correctly stored in word1 and word2.

#include <stdio.h>
int main(void)
{
    char word1[10];
    char word2[10];
    scanf("%9s", word1);
    scanf("%9s", word2);
    printf("%s
", word1);
    printf("%s
", word2);
}

What is the problem with using pointers with scanf?

question from:https://stackoverflow.com/questions/65878284/difference-between-scanf-for-char-and-char

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is the problem with using pointers with scanf?

The first one is undefined behaviour. Look at this part of code:

char *word1;
char *word2;
scanf("%s", word1);
scanf("%s", word2);

No memory allocated to word1 and word2 pointers. When you give input, scanf() end up accessing unallocated pointers and dereferencing an unallocated/invalid pointer is undefined behaviour.

You should make sure that before using/accessing a pointer, it should be pointing to a valid memory location. You can either make it point to an exiting valid memory or allocate memory dynamically to it, like this:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *word1;
    char *word2;

    word1 = malloc (10);
    if (word1 == NULL) {
        exit (EXIT_FAILURE); // or whatever you want to do to handle memory allocation failure
    }
    word2 = malloc (10);
    if (word2 == NULL) {
        exit (EXIT_FAILURE); // or whatever you want to do to handle memory allocation failure
    }

    scanf("%9s", word1);
    scanf("%9s", word2);
    printf("%s
", word1);
    printf("%s
", word2);

    // once done with allocated memory, free it
    free (word1); 
    free (word2);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...