How do I use char* variable type in C?

Discussion in 'C' started by techme, Mar 27, 2010.

  1. techme

    techme New Member

    Joined:
    Feb 15, 2010
    Messages:
    86
    Likes Received:
    0
    Trophy Points:
    0
    I am a beginner.The following code in Microsoft Visual C++ 6.0 IDE gives out an error.
    It compiles with no errors and no warnings.
    Then makes with no errors and no warnings.
    But displays a dialog box showing that there is an error and asking to report it to Microsoft.

    What is the correct usage of char*?
    Can anybody please help me?
    Code:
    #include <stdio.h>
    void main(){
       char* yourName;
       printf("Please enter your name: ");
       scanf("%s", &yourName);
       printf("\nWelcome %s, I was waiting for you!\n", yourName);
    }
    
     
  2. meyup

    meyup New Member

    Joined:
    Feb 15, 2010
    Messages:
    102
    Likes Received:
    0
    Trophy Points:
    0
    try this code.
    Code:
    #include <stdio.h>
    void main(){
    char* yourName;
    printf("Please enter your name: ");
    scanf("%s", yourName);
    printf("\nWelcome %s, I was waiting for you!\n", yourName);
    }
    As you have declared a pointer which points a character.
    Code:
    char* yourName;
    Now you are getting a value from the user and trying to store it in pointer type variable. scanf() function takes the address of the variable i.e. pointer to that variable and store the input. As you have already declared the pointer and you code scanf("%s", &yourName); is trying to save that input value in the address of that pointer. Which is logically incorrect. Your code looks fine and no error but it has a logical mistake that is why it compiles fine but gives error at runtime. You code should look like scanf("%s", yourName);
     
  3. techme

    techme New Member

    Joined:
    Feb 15, 2010
    Messages:
    86
    Likes Received:
    0
    Trophy Points:
    0
    Thanks!
    That works well!!

    Thank you for taking your time, and nice brief explanation.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice