代码之家  ›  专栏  ›  技术社区  ›  Wizard

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

  •  -1
  • Wizard  · 技术社区  · 6 年前

    &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����
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Azeem Rob Hyndman    6 年前

    您需要使用 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