以下代码示例不会打印 main() 函数中
array
中包含的字符串 test1
- test5
但是它在 make() 函数内工作
我确信答案很简单,我该如何产生想要的结果?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 4
void make(char ***array) {
char p2[] = "test1 test2 test3 test4 test5";
char* token = strtok(p2, " ");
int i = 0;
while (token)
{
(*array)[i]= token;
token = strtok(NULL, " ");
i++;
}
printf("%s\n",(*array)[0]);
printf("%s\n",(*array)[1]);
printf("%s\n",(*array)[2]);
printf("%s\n",(*array)[3]);
printf("%s\n",(*array)[4]);
}
int main(int argc, char **argv) {
char **array;
make(&array);
int i;
for (i = 0; i < ELEMENTS; ++i) {
printf("%s\n", array[i]);
}
return 0;
}
此代码编译时没有错误或警告,并生成以下输出:
test1
test2
test3
test4
test5
yf�
���
我的预期结果是 test1 - test5
打印两次,一次在 make() 函数内
,一次在 main() 函数内
>
作为旁注,这只是我在 stackoverflow 上发布的第二篇文章,这是我第一个问题 Passing a string array to a function in C 的修改代码
最佳答案
char p2[] = "test1 test2 test3 test4 test5";
在make()
函数的堆栈上定义字符串p2。 strtok()
只返回指向同一个数组的指针,当 make()
返回时该指针无效。
与此相同:
char * foo()
{
char array[] = "hello";
printf("%s\n", array); // works fine
return array;
}
void main()
{
char * array = foo(); // just a pointer to invalid data
printf("%s\n", array); // FAIL
}
如何正确执行
在 C 中返回字符串基本上有两种方法。
通过填充缓冲区:
void fill_buf(char * buf, size_t len)
{
char string[] = "hello";
snprintf(buf, len, "%s", string);
}
void main()
{
char buffer[25];
fill_buf(buffer, sizeof(buffer));
printf("%s\n", buffer);
}
或者通过返回 malloc 的字符串:
char * get_malloced_or_null()
{
char my_string[] = "hello";
char * copied_pointer = strdup(my_string); // might fail and return NULL
return copied_pointer;
}
void main()
{
char * string = get_malloced_or_null();
if (string == NULL) { return; }
printf("%s\n", string);
free(string);
}
第二种方法的优点是您可以将其与任意长的字符串一起使用。另一方面,您需要检查分配失败,并且在使用完毕后必须释放内存。
关于c - 修改函数内部的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837679/