为什么这行给出不会给出指针的地址? [英] Why wouldn't this line of give give the address of the pointer?

查看:102
本文介绍了为什么这行给出不会给出指针的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于:


int main(无效){


char * ptr =" test me";

printf("%s \ n",& ptr [0]);

}

为什么输出为

测试我


我想&给出了指针的地址。为什么这会产生

字符串?

Given:

int main(void) {

char *ptr = "test me";
printf("%s\n", &ptr[0]);
}
Why would the output be
test me

I thought & gave the address of the pointer. Why does this yield the
string?

推荐答案

ptr [0]是第一个字符串string和& ptr [0]是它的地址,这是%s预期的
。试试:


printf("%lx \ n",(long)& ptr);


代替: - )
ptr[0] is the first char of the string and &ptr[0] is its address, which is
what %s is expecting. Try:

printf("%lx\n", (long)&ptr);

instead :-)


grocery_stocker< cd ***** @ gmail.com>写道:
grocery_stocker <cd*****@gmail.com> wrote:
给定:
int main(void){
char * ptr =" test me" ;;
printf("%s \ n" ,& ptr [0]);
}


你在这里错过了一个返回声明,你答应了main()

返回一个int,不是吗?

为什么输出会测试我
我想&给出了指针的地址。为什么这会产生
字符串?
Given: int main(void) { char *ptr = "test me";
printf("%s\n", &ptr[0]);
}
You''re missing a return statement here, you promised that main()
returns an int, didn''t you?
Why would the output be
test me I thought & gave the address of the pointer. Why does this yield the
string?




好​​吧,''ptr''是指向(字符串的第一个元素)的指针。但是

你在它之前加上'[0]'和它之前的''&''。并且

''[]''运营商绑定比地址运算符强,你会用
来改变它。所以''ptr [0]''首先被评估为
,导致数组的第一个元素。然后在&b
前面的''&''使它成为第一个元素的指针。所以

''ptr''和''& ptr [0]''是相同的(除了在第二种形式中

你必须输入一个更多)。

问候,Jens

-

\ Jens Thoms Toerring ___ Je *********** @ physik.fu-berlin.de

\ __________________________ http://www.toerring.de


Mick Sharpe写道:
Mick Sharpe wrote:
ptr [0]是字符串的第一个字符,& ptr [0]是它的地址,
是%s期待。尝试:

printf("%lx \ n",(long)& ptr);
ptr[0] is the first char of the string and &ptr[0] is its address, which is what %s is expecting. Try:

printf("%lx\n", (long)&ptr);




实际上,这可能是更好:


printf("%p \ n",(void *)& ptr);


如果代表指针的关键并不重要。


指向整数类型的指针的转换是实现

最好定义的行为,最坏的未定义行为(如果指针

不能表示为指定的整数类型。)


Rob Gamble



Actually, this would probably be better:

printf("%p\n", (void *)&ptr);

if the representation of the pointer is not critical.

The conversion of a pointer to an integer type is implementation
defined behavior at best, undefined behavior at worst (if the pointer
cannot be represented as the specified integer type).

Rob Gamble


这篇关于为什么这行给出不会给出指针的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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