An overview of reading a string from 'USER' using pointer (char *) & array (char[])

It's my long pending posts of how to get the input string from the user. It is a fundamental. 

Reading a char pointer

#include<stdio.h>

void main(){
    char *string;
    printf("Enter the string : ");
    scanf("%s", string);
    printf("Entered string %s\n", string);
    return; 

} 

Output

Enter the string : Shirley
Entered string (null)

Here, the compiler gives a NULL value  as the pointer doesn't point anywhere.

In some of the cases, compiler might accept smaller length input like 'Shirley'. But, If the input is 'ShirleyShirleyShirley',  mostly you will get a runtime error 'main.c stopped working unexpectedly'.  In this case, it is called buffer overflow which defines your input is larger than the boundaries of the buffer.

Buffer overflow can be managed by
         scanf("255%s", string);


#include<stdio.h>
#include<stdlib.h>
void main(){
    char *string;
    string = malloc(255);
    printf("Enter the string : ");
    scanf("%s", string);
    printf("Entered string %s\n", string);
    free(string);
    return;
}

Output

Enter the string : Shirley
Entered string Shirley


Reading a char array

#include<stdio.h>

void main(){
    char string[10] = {'\0'};
    printf("Enter the string : ");
    scanf("%s", string);
    printf("Entered string %s\n", string);
    return;
}

Output

Enter the string : Shirley
Entered string Shirley


 

Comments