Search code examples
carrayspointersc-strings

How to read and print number and string using pointers?


I'm recollecting my C programming skills after 1 year. So I decided to start from scratch. I got stuck with this program. very grateful for help. Thanking you in advance.

Here's is my code.

/*Reading a number and string and printing on screen using pointers*/
#include <stdio.h>
main()
{
int number, *ptr,*ptr2;
char string[20];

ptr=&number;
ptr2= &string;

printf("Enter a number");
scanf("%d",&number);
printf("Enter a string");
scanf("%s", string);
printf("Your number is: %d\n", *ptr);
printf("String is %s \n", *ptr2);
}

It is asking for input after that it's printing number not printing string. Instead of string it's showing Segmentation fault.

The above program is to read and printing number and name from user. This is expecting program but it's not working properly.


Solution

  • In your program, ptr2 declared as an integer pointer and you are pointing it to a string. ptr2 should be of type char *.

    In this statement:

    ptr2= &string;
    

    You don't need to give & operator before array name. An array name converts to a pointer that point to the initial element of the array object. So, it should be:

    ptr2 = string;
    

    If you are using scanf to take input string from user, make sure guard against buffer overflow. Check this and this.

    You can do:

    #include <stdio.h>
    int main()
    {
        int number, *ptr;
        char *ptr2;
        char string[20];
    
        ptr = &number;
        ptr2 = string;
    
        printf("Enter a number: ");
        scanf("%d",&number);
        printf("Enter a string: ");
        scanf("%s", string);
        printf("Your number is: %d\n", *ptr);
        printf("String is: %s\n", ptr2);
        return 0;
    }
    

    Good to go through it once :
    Best way to get input from the user in C.