为什么 scanf 不需要字符串的&符号并且在 printf (在 C 中)中也可以正常工作? [英] Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)?

查看:11
本文介绍了为什么 scanf 不需要字符串的&符号并且在 printf (在 C 中)中也可以正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习 C 中的字符串.

I am learning about strings in C now.

如何使用scanf来获取你可以做的字符串

How come to use scanf to get a string you can do

scanf("%s",str1);

对于 printf 你可以做到

and for printf you can do

printf("The string is %s
", str1);

我知道对于 scanf 来说,这是因为字符串只是一个字符数组,它是一个指针,但是对于 printf,你怎么能像输入 int 或 float 一样输入变量名?

I understand that for scanf it is because the string is just a character array which is a pointer, but for printf, how is it that you can just put the variable name just like you would for an int or float?

推荐答案

scanf 需要读入变量的地址,而字符串缓冲区已经表示为地址(指向内存中某个位置的指针,或分解为指针的数组).

scanf needs the address of the variable to read into, and string buffers are already represented as addresses (pointer to a location in memory, or an array that decomposes into a pointer).

printf 做同样的事情,把 %s 当作一个指向字符串的指针.

printf does the same, treating %s as a pointer-to-string.

这篇关于为什么 scanf 不需要字符串的&符号并且在 printf (在 C 中)中也可以正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆