2
votes

I am reading C for Dummies and am doing a example in the book. It told me to write it out line by line. Then it proceeds through the book even though the code has bugs. Here it is:

#include <stdio.h>

int main()
{

char me[20];
printf("What is your name?");
scanf("%s",&me);
printf("Darn glad to meet you. %s!\n".me);

return(0);

}  

According to gcc:

WHORU.C: In function ‘int main()’: WHORU.C:8:19: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘char (*)[20]’ [-Wformat] WHORU.C:9:43: error: request for member ‘me’ in ‘"Darn glad to meet you. %s!\012"’, which is of non-class type ‘const char [28]’

Because I am new to C, I can't really point out where I did wrong. I do know that this code requires input when it's executed. It's kinda like scanner in java.

Thanks guys.

3

3 Answers

3
votes
scanf("%s",&me);

Should be:

scanf("%s",me);

scanf() receives a pointer to the variable you passed. But in C, an array decays to pointer when passed, hence no need of &.

Another error is, you have a . in the printf which should be a ,.

printf("Darn glad to meet you. %s!\n".me);

should be:

printf("Darn glad to meet you. %s!\n",me);
2
votes

You just use scanf("%s",me); that should solve your problem . In C me[] is equivalent to *me.

0
votes

I would hazard a guess that scanf("%s",&me); should be scanf("%s",&me[0]) or scanf("%s",me) because &me is a pointer to an array of chars, whereas &me[0] is a pointer to a single char at the beginning of an array of chars. I personally prefer the first way to do it because it seems more logical to me as in "Take the address of the first char in the array me"

Additionally, printf("Darn glad to meet you. %s!\n".me); should probably have a comma, not a period between the string and "me" because me is an argument to the printf function. When you use a period, it's looking for a member on the string "Darn glad to meet you. %s!\n" called "me" which doesn't exist. You would have the same problem in java, so I'm guessing this one is just a typo.