cscanfchar-pointer

Storing a string in char pointer (using scanf)


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


int main(){

    char *s1;
    char *s2;

    printf("Enter the string : ");
    scanf("%s",s1);

    printf("Enter the string : ");
    scanf("%s",s2);

    return 0;
}

I'm facing problems in taking inputs in char pointer. Here I'm just taking 1 word as input but Scanf isn't taking any inputs at all when using char pointer, but works well with char arrays. Is it a code blocks bug?


Solution

  • A pointer is a variable that holds a memory address.

    An uninitialized variable contains (generally) some random garbage number.

    When you pass some random garbage number to scanf and tell it to store a string at that address, it's no surprise that (usually) the program crashes.

    It makes no sense to tell scanf to store a string at an address where you don't know what the address is. It's like telling your friend to come over to your house and when they ask which house is yours, you click somewhere random on Google Maps. It's probably going to be in the middle of the ocean or something and they'll drown.

    What you need to do is make a space to put the string (such as by declaring an array) and then tell scanf to put the string in that space that you specifically made to hold the string.

    A pointer to a string does not hold the string. A pointer to a string is just a signpost saying "the string is over there --->", and you can change it if you want it to point to a different place, maybe holding a different string, but it's never going to hold a string itself.