简体   繁体   English

与printf一起使用时,C中的char *和int *之间的区别

[英]difference between char* and int* in C when used with printf

This could be a very basic question, but I am not able to understand it. 这可能是一个非常基本的问题,但我无法理解。 I need a clear understanding, hence am posting here. 我需要清楚的了解,因此请在此处发布。

Consider the code: 考虑一下代码:

char *c = "hello";
int   a = 10;
int  *b = &a;
printf("%s\t%d\n", c, *b);

Why do I have to pass *b to get value to be printed but in case of strings if I just give c printf still prints "hello"? 为什么我必须传递*b才能获得要打印的值,但是如果我只给c给出字符串,则printf仍会打印“ hello”?

That's just what the specifiers mean: 这就是说明者的意思:

  • %s wants a pointer to a char, so you don't have to dereference it, printf will %s一个指向char的指针,因此您不必取消引用它, printf
  • %d wants a true integer so you do have to dereference it %d想要一个真正的整数,这样你必须取消对它的引用

It's just what printf is and always was. 这就是printf一直以来都是的。

Because that's how printf is defined. 因为那是printf的定义方式。

But it makes sense; 但这是有道理的; consider the following code: 考虑以下代码:

printf("%d\n", 42);

What would the equivalent code be if printf took integers via pointer? 如果printf通过指针获取整数,等效代码是什么?

Strings are a special case; 字符串是一种特殊情况。 a string in C is a sequence of characters in memory, accessed via a pointer to its first element. C中的字符串是内存中的字符序列,可通过指向其第一个元素的指针进行访问。 So you need to give printf that pointer, so that it can read the whole string. 因此,您需要给printf该指针,以便它可以读取整个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM