通过引用传递字符指针数组的混淆

标签 c pointers local-variables

如何通过引用传递字符指针数组?我尝试使用 &tokens 传递并在 func() 中取消引用,但它仍然不起作用。

这是我的代码:

#include <stdio.h>

void func(char* tokens[10])
{
    char word[10] = "Hello\0";
    tokens[0] = word;
}

int main()
{
    char* tokens[10];

    func(tokens);
    printf("%s", tokens[0]);

    return 0;
}

结果:

He����

最佳答案

您需要使用 malloc() 动态分配内存返回并稍后使用 free() 取消分配它。从函数返回局部变量是不正确的,因为该内存位于堆栈上,并且在函数完成执行时将不可用。

这是您的工作代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void func(char* tokens[10])
{
    char* word = malloc( 10 );
    strcpy( word, "Hello!" );
    tokens[0] = word;
}

int main() 
{
    char* tokens[10];

    func(tokens);
    printf("%s", tokens[0]);

    free( tokens[0] );

    return 0;
}

输出:

Hello!

以下是实例:https://ideone.com/LbN2NX

关于通过引用传递字符指针数组的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016628/

相关文章:

c - 函数调用的评估顺序

c - 释放大数组指针时出现段错误

objective-c - 通过派生指针调用基类函数

c - 用 C 读取和写入 .bin 文件

c - 如何通过函数设置指针引用

ruby - 如何创建没有命名空间污染的作用域

Perl Map block 局部变量的使用

c++ - 当我想修改指向常量整数的指针时,为什么我的编译器不显示错误?

c - 奇怪的宏扩展

c - Linux/include 目录枚举