Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between scanf for char * and char [ ]?

Tags:

c

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\n", word1);
    printf("%s\n", 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\n", word1);
    printf("%s\n", word2);
}

What is the problem with using pointers with scanf?

like image 348
wn5865 Avatar asked Mar 01 '23 18:03

wn5865


2 Answers

There is no problem in with using a pointer as your scanf argument in principle. In your specific case, you've simply not initialized those pointers, so you're causing undefined behaviour. Modifying your second (correct) example to use pointers:

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

The important thing to remember about pointers is that they have to point to something in order to be useful.

like image 190
Carl Norum Avatar answered Mar 04 '23 06:03

Carl Norum


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\n", word1);
    printf("%s\n", word2);

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

    return 0;
}
like image 27
H.S. Avatar answered Mar 04 '23 08:03

H.S.