加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中传递char指针

发布时间:2020-12-16 09:49:38 所属栏目:百科 来源:网络整理
导读:我正在学习C中的指针,所以我这样做是为了查看我在做某事时应该希望的输出.这里是: int characters(char temp[]){ printf("nAddress of string by temp: %p",temp); printf("nAddress of string by temp: %p",temp); printf("nContent of string: %s",tem
我正在学习C中的指针,所以我这样做是为了查看我在做某事时应该希望的输出.这里是:

int characters(char temp[])
{
    printf("nAddress of string by &temp: %p",&temp);
    printf("nAddress of string by temp: %p",temp);
    printf("nContent of string: %s",temp);     
    return 0;
}
int main()
{
    char s[] = "Prafulla Shahi";
    char *t=s;
    clrscr();
    characters(t);
    printf("nMainnAddress of string by &s: %p",&s);
    printf("nAddress of string by s: %p",s);
    printf("nContent of string: %s",s);
    printf("nAddress of pointer by &t: %p",&t);
    printf("nAddress of pointer by t: %p",t);
    printf("nContent of pointer: %s",t);
    getch();
    return(0);
}

我得到的输出是这样的:

Address of string by &temp: 0x7fff4ab45788
Address of string by temp: 0x7fff4ab457b0
Content of string: Prafulla Shahi    
Main
Address of string by &s: 0x7fff4ab457b0
Address of string by s: 0x7fff4ab457b0
Content of string: Prafulla Shahi
Address of pointer by &t: 0x7fff4ab457a8
Address of pointer by t: 0x7fff4ab457b0
Content of pointer: Prafulla Shahi

我的问题是:
当temp&temp和temp询问时,临时数组的地址显示两个不同的值?

我的理解是,temp是一个数组变量,但它有自己的地址(与指针t类似的行为.为什么它的行为不像通常的变量数组?). main()中的数组s []也是一个数组,但是当& s和s调用时,它的地址显示相同的值.

有人可以解释一下吗?

解决方法

char s[] = "Hello world";

s是一个数组对象(用字符串文字初始化).数组的地址和数组的第一个元素的地址是相同的(只有类型不同).

所以:

(char *) &s == s  /* value of the == expression is 1 */

但:

char *p = "Hello world";

p是指针对象(指向字符串文字). p的地址是指针对象的地址,该地址不同于p的值,p是指向“Hello world”字符串的第一个字符的指针.

所以:

(char *) &p == p  /* value of the == expression is 0 */

为了完整回到您的示例,我还必须补充说,函数声明中的数组参数在C中调整为指针类型的参数.所以这两个函数声明是等价的:

int characters(char temp[]) { /* ... */ }

int characters(char *temp) { /* ... */ }

这也意味着内部字符功能,我们有:

(char *) &temp == temp  /* value of the == expression is 0 */

因为temp是指针对象而不是数组对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读