So my code is:
#include <stdio.h>
int main() {
char ch[5] = "funny";
printf("gum: ");
printf("ze numbre is %c \n", ch);
}
as far as I learned, it should print:
gum: ze numbre is funny
but instead of outputting the ch
variable, if outputs some strange symbol (it looks like a small red square with square FF and sometimes F5 written on it), any tip? I'm coding in VSCode
CodePudding user response:
The problem is the printf
conversion specifier %c
expects a single character passed as an int
such as 'c'
. You are passing ch
, an array of char
, which is automatically converted to a pointer to its first element when passed as a function argument. You should use %s
for this argument.
Note also that char ch[5] = "funny";
does not create a proper C string as there is not enough space in ch
for the 5 characters in funny
and the null terminator. It is safer to let the compiler compute the length of the array with
char ch[] = "funny";
You could also define a char
pointer and initialize it to point to a string literal:
char *ch = "funny";
Here is a modified version:
#include <stdio.h>
int main() {
char ch[] = "array";
const char *p = "pointer";
printf("gum: ");
printf("ch is an %s\n", ch);
printf("p is a %s\n", p);
return 0;
}
CodePudding user response:
First I compiled your code :
gcc c.c -Wall
c.c: In function ‘main’:
c.c:7:27: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
7 | printf("ze numbre is %c \n", ch);
| ~^ ~~
| | |
| int char *
| %s
Then changed c to s ( as compiler and Fred Larson said):
#include<stdio.h>
int main(){
char ch[5] = "funny";
printf("gum: ");
printf("ze numbre is %s \n", ch);
}
then recompile ( no errors ) and run
gcc c.c -Wall
./a.out
gum: ze numbre is funny
Works as expected ... but it still not error free as Ed Heal and Fred Larson said: it can give undefined behavior. So next try: let "the compiler to calculate the length of the array"
#include<stdio.h>
int main(){
char ch[] = "funny";
printf("gum: ");
printf("ze numbre is %s \n", ch);
}
You can do it in explicit way
char ch[6] = {'f', 'u', 'n', 'n', 'y', '\0'};
or manually udjust length of the array ( include one place for null sign, which is is added automatically at the end of each string in C.
char ch[6] = "funny";
There is also another way
#include<stdio.h>
int main(){
char ch[5] = "funny";
printf("gum: ");
printf("ze numbre is %.5s \n", ch);
}
Is it good ?