-
printing char* strings
I'm trying to print a string stored in a char* variable. The contents are coming out correctly except that there's funny ASCII symbols printed at the end......
Variable: char* temp;
Reading: scanf("%s",&temp);
Printing: printf("%s",&temp);
What am I doing wrong?
-
-
>> What am I doing wrong?
1) Variable: char* temp;
temp doesn't point to any memory.
2) Reading: scanf("%s",&temp);
scanf("%s", temp);
3) Printing: printf("%s",&temp);
as Azuth said.
-
>char* temp;
This is wrong. temp needs to point to addressable memory before you do anything with it. You can do so like this:
Code:
char *temp = malloc(15 * sizeof *temp);
This allocates memory for 15 characters (14 content characters and the trailing null character since you want a string). Now you can move on to the next line.
>scanf("%s",&temp);
This is wrong. scanf always requires a pointer, but because temp is already a pointer, applying the address-of operator is not what you want to do. Also, %s will read any number of characters up to whitespace or EOF (or error), and copy them happily to the variable you give it. This is a problem if scanf reads more characters than you have space for. You can force %s to stop through a field width modifier:
Code:
scanf("%14s", temp);
This reads (at most) 14 characters, and appends a null character when it's done. The reason I used 14 instead of 15 is to leave scanf one cell for the final character that makes the sequence of characters a string. Remember that strings are like this:
Code:
't', 'e', 's', 't', '\0'
Even though the '\0' isn't used except as a sentinel, you still need to have space for it. Now that you've safely read a string, you can print it.
>printf("%s",&temp);
This is wrong. printf rarely needs the address-of operator for it's format modifiers, but conveniently enough, %s is one of them. The problem is that temp is already a pointer, just like with scanf. You need to remove the ampersand:
Code:
printf("%s\n", temp);
Also notice that I put in a'\n' character at the end of the format string. This is because some systems may not flush the stream until later and the string may appear at an odd time. This is most noticeable in interactive prompts for input where the stream isn't flushed before the input request, so the user doesn't see it and has no idea what to do.
A newline always causes the output stream to be flushed, as does a call to fflush. Be sure to remember that even if your system happens to do the right thing without them. :)
-
Thanks, got it working and I understand now!