如何通过引用传递字符指针数组?我尝试使用 &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!
关于通过引用传递字符指针数组的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016628/