c - 在 C 中传递字符指针

标签 c arrays function pointers

我正在学习 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("\nMain\nAddress 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的行为。为什么它的行为不像通常的变量数组s?)。 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世界” 字符串。

所以:

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

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

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

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

这也意味着在 characters 函数中,我们有:

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

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

关于c - 在 C 中传递字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793343/

相关文章:

php - 选择数组中的位置

javascript - 在数组中的两个项目之间进行检查的更好方法

javascript - 如何将一个html的值返回到另一个html

c - 编译 pshtoolkit 的问题

c - 如何在 ftrace 中打印 trace_printk 的完整跟踪文件?

c - 在 C 语言中如何最好地格式化非常长的字符串常量?

function - 如何在 Emacs 中将 F1-F12 键绑定(bind)为键盘宏?

c - 使用输入包含括号的字符串作为命令行参数时出错

php - 在 PHP 中使用资源作为数组索引

sql - 如何创建pl sql函数以检查数据库中是否存在数据