Thread: need help about string in c program

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    8

    Exclamation need help about string in c program

    Code:
    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char *p;
        printf("enter some thing:");
        gets(p);
        printf("you have typed:%s\n",p);
    
    }
    why this program not work? i can't use pointer as a string.
    output this program is
    enter some thing:raihan
    Segmentation fault (core dumped)

    i get all time this error "Segmentation fault (core dumped)" error all-time if i use pointer as a string. how i solve this problem? am using code-blocks on Linux mint13 KDE.

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Your variable p is a pointer.
    Q: where does it point to?
    A: nowhere, it hasn't been initialized or assigned anything.

    Suggestion: make it point to somewhere valid and with enough space for your needs.
    Suggestion 2: do not use gets(), use fgets() instead (and remove the final '\n' if needed). It is impossible to use safely and it doesn't exist in the most recent version of the language.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    As qny pointed out, the pointer is pointing to nothing valid, so far. If you want to use a pointer like this, maybe use malloc() or calloc(), to give you a valid address for the pointer, AND at the same time, to give you memory to store your string.

    A pointer holds an address - but even if that address is good, it ALSO needs that address to point to a valid block of memory, for the string. Make sense?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Program
    By ishwariamca in forum C++ Programming
    Replies: 11
    Last Post: 09-17-2008, 11:32 PM
  2. Help with string program
    By Duskan in forum C Programming
    Replies: 8
    Last Post: 04-02-2007, 08:27 AM
  3. String program
    By howdy_doody in forum C Programming
    Replies: 2
    Last Post: 03-13-2005, 07:01 PM
  4. Small string program help please
    By learning C++ in forum C++ Programming
    Replies: 8
    Last Post: 12-30-2003, 10:19 AM
  5. need help with C-string program
    By fritz83 in forum C++ Programming
    Replies: 10
    Last Post: 12-02-2003, 12:32 AM

Tags for this Thread