可以指向一个字符串printf的使用? [英] Can a pointer to a string be used in a printf?
问题描述
我想到的是这样的:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void) {
//test pointer to string
char s[50];
char *ptr=s;
printf("\nEnter string (s): ");
fgets(s, 50, stdin);
printf("S: %s\nPTR: %s\n", s, *ptr);
system("PAUSE");
return 0;
}
或者我应该使用一个for循环与*(S + i)和格式说明%C?
这是唯一可行的方法来通过指针和一个简单的printf打印字符串?
Or should I use a for loop with *(s+i) and the format specifier %c? Is that the only possible way to print a string through a pointer and a simple printf?
更新:printf的与数组的第一个元素的工作ADRESS,所以当我用* PTR其实,我的第一个元素进行操作,而不是它的ADRESS。谢谢你。
推荐答案
的%S
格式说明符的printf
的总是的期望一个的char *
参数。
The "%s"
format specifier for printf
always expects a char*
argument.
假设:
char s[] = "hello";
char *p = "world";
printf("%s, %s\n", s, p);
它的看起来的就像你传递数组的第%S
和第二的指针,但实际上你(正确地)传递指针为。
it looks like you're passing an array for the first %s
and a pointer for the second, but in fact you're (correctly) passing pointers for both.
在C,数组类型的任何前pression被隐式转换为指向数组的第一个元素的除非的它在以下三种情境之一:
In C, any expression of array type is implicitly converted to a pointer to the array's first element unless it's in one of the following three contexts:
- 这是一个参数传递给一元&放大器; (地址)的运营商
- 这是一个参数传递给一元的sizeof运算符
- 这是一个字符串中用于初始化数组对象的初始化。
(我认为C ++有一个或两个其他异常。)
(I think C++ has one or two other exceptions.)
的printf()的实现
看到%S
,假定相应的参数是一个指针为char,并使用该指针来遍历字符串,并打印出来。
The implementation of printf()
sees the "%s"
, assumes that the corresponding argument is a pointer to char, and uses that pointer to traverse the string and print it.
的 comp.lang.c常见问题解答部分6有这样的一个极好的讨论。
Section 6 of the comp.lang.c FAQ has an excellent discussion of this.
这篇关于可以指向一个字符串printf的使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!