使用指针在C打印字符串
我只是在打印C.一些字符
我宣布字符c和分配的字符。
然后用一个for循环我尝试打印的人物一个接一个。
我已经使用指针,当然。
I was just printing some characters in C. I have declared char c and assigned its characters. then using a for loop i try to print the characters one by one. I have used pointers, of course.
#include <stdio.h>
#include <string.h>
int main()
{
char c[4] = {"hia"};
int i;
for(i=0;i<4;i++)
{
printf(&c[i]);
}
return 0;
}
然而,当我使用涡轮编译我的code,我得到的输出hiaiaa而不是HIA!我究竟做错了什么?
However when I compile my code using turbo, i get output "hiaiaa" instead of "hia"! What am i doing wrong here?
您的printf()
电话坏了。您正在使用的字符串(从点指定)作为格式化字符串。这将不打印单个字符。相反,每次调用将打印在那里它的格式字符串开始,结束的字符串。
Your printf()
call is broken. You are using the string (from the point you specify) as the formatting string. This will not print single characters. Instead each call will print from where its formatting string starts, to end of the string.
这意味着第一次调用会打印所有的的ç
,接下来会从打印C [1]
和起,并依此类推。不是在所有你想要的东西。
This means the first call will print all of c
, the next will print from c[1]
and onwards, and so on. Not at all what you wanted.
如果您想打印单个字符,请使用%C
格式说明:
If you want to print single characters, use the %c
format specifier:
printf("%c", c[i]);
没有指针必要的,因为性格是按值传递给的printf()
。
No pointer necessary, since the character is passed by value to printf()
.