混淆通过引用传递字符指针数组
Confusion with passing character pointer array by reference
如何通过引用传递字符指针数组?我尝试使用 &tokens
传递并在 func()
中取消引用,但它仍然不起作用。
这是我的代码:
#include <stdio.h>
void func(char* tokens[10])
{
char word[10] = "Hello[=10=]";
tokens[0] = word;
}
int main()
{
char* tokens[10];
func(tokens);
printf("%s", tokens[0]);
return 0;
}
结果:
He����
您需要使用 malloc()
to return and later de-allocate it using 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!
如何通过引用传递字符指针数组?我尝试使用 &tokens
传递并在 func()
中取消引用,但它仍然不起作用。
这是我的代码:
#include <stdio.h>
void func(char* tokens[10])
{
char word[10] = "Hello[=10=]";
tokens[0] = word;
}
int main()
{
char* tokens[10];
func(tokens);
printf("%s", tokens[0]);
return 0;
}
结果:
He����
您需要使用 malloc()
to return and later de-allocate it using 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!