Friday, July 31, 2009

How do I use char* variable type in C?

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 %26lt;stdio.h%26gt;





void main(){


char* yourName;


printf("Please enter your name: ");


scanf("%s", %26amp;yourName);


printf("\nWelcome %s, I was waiting for you!\n", yourName);


}

How do I use char* variable type in C?
A char* is a pointer (*) to a bunch of characters (char). But before you can use it the way you want to, you have to make sure that the pointer points to an memory area that is free to store characters in.





Try it like this:





//code...


#include %26lt;stdio.h%26gt;





int main(int argc, char *argv[])


{


   char* yourName = malloc(20 * sizeof(char));


   printf("Please enter your name: ");


   scanf("%s", %26amp;yourName);


   printf("\nWelcome %s, I was waiting for you!\n", yourName);


   free(yourName);


}





This code reserves enough space for 20 characters and you may need to include %26lt;alloc.h%26gt; or something --it's been a while since I last programmed in C...
Reply:ummmmm, It's strange one really :D





I will keep on fixing it
Reply:You have declared yourName but not given it any memory. You could say





char yourName[maxLengthofName];
Reply:A char * is a pointer. You have not initialized to point to an address so it will put the name you enter into random memory. Or windows will prevent you from accessing the memory and put up the error you see. So





//code...


#include %26lt;stdio.h%26gt;





void main()


{


char yourName[256]; // give yourself some space in this array





printf("Please enter your name: ");


scanf("%s", yourName); // yourName is an address.


printf("\nWelcome %s, I was waiting for you!\n", yourName);


}





OR if you need to use char *


void main()


{


char yourName[256]; // give yourself some space in this array


char * ptr = yourName; // the address


printf("Please enter your name: ");


scanf("%s", ptr); // ptr is an address of the yourName Array.


printf("\nWelcome %s, I was waiting for you!\n", ptr);


}





Give either of these a try!
Reply:Hi, Here when you define





"char * yourName;"





'yourName' will store the address where the value will be stored...





just change the scanf statement, remove '%26amp;' sign as 'yourName' already contains the address on your memory..





"scanf("%s", yourName);"


No comments:

Post a Comment