首页 > 解决方案 > 为什么我不能传递指针而不是指向函数的指针?

问题描述

我有以下程序想要修改以便我们可以在最后s打印出来"Hello World!"

#include <stdio.h>

// modify this function
void function(char** c)
{
    *c = "Hello World!";
}

int main()
{
    char* s;
//    function(&s); 
    function(s);
    puts(s);
    return 0;
}

通常,我们会这样做function(&s)。但是,我的问题是为什么我们不能只使用function(s)?当然,这样做会在编译期间引发警告,但由于s包含内存地址 say 0xab。如果我们修改0xabfrom 0x00to上的内容"hello world!",hold by 的地址s不会改变,我们仍然应该看到"Hello World!"消息。

我想知道为什么function(s)在这种情况下不起作用?我在 Mac 上编译程序。

参考:

标签: c

解决方案


s 未初始化,因此它包含一些垃圾地址(可能是无效地址)。

当您这样做时,*s = "Hello World!";您正在向某个垃圾地址(可能是无效地址)写入"Hello World!"(这是一个指针值)。

假设它没有崩溃 - 然后puts将从同一个垃圾地址读取字节(即它将读取字符串的地址,而不是字符串)并将它们显示在屏幕上。

运行不正确的代码后,内存可能包含这些值,例如:

Address      Value (4 bytes at a time)
...
0x12345678   0x65401234      <- some important thing you just overwrote that is liable to make your program crash,
                                now it holds the address of the string literal
...
0x4000000C   0x12345678      <- variable 's' in main
0x40000010   0x12345678      <- variable 's' in function, copy of variable 's' in main
...
0x65401234   'H', 'e', 'l', 'l'  <- where the compiler decided to put the string literal
0x65401238   'o', ' ', 'W', 'o'
0x6540123C   'r', 'l', 'd', '!'
0x65401240   0

当你打电话时,puts(s);你会打电话puts(0x12345678);,它会打印字节0x65401234(但它不会打印“0x65401234”,它会尝试打印与那些对应的字母)

如果你做对了,你最终会得到:

Address      Value (4 bytes at a time)
...
0x4000000C   0x65401234      <- variable 's' in main
0x40000010   0x4000000C      <- variable 's' in function, has address of variable 's' in main
...
0x65401234   'H', 'e', 'l', 'l'  <- where the compiler decided to put the string literal
0x65401238   'o', ' ', 'W', 'o'
0x6540123C   'r', 'l', 'd', '!'
0x65401240   0

然后puts(s)puts(0x65401234)哪个打印字符串。


推荐阅读