第一次尝试:
char* loadValues (char* str) {
char* toReturn[5];
.. some operations here ..
return toReturn
}
这显然会返回警告并且无法正常工作,因为函数完成后内存位置将被释放。
所以我想到了使用 malloc,但是,我不明白它如何与数组一起工作。
第二次尝试:
char* loadValues (char* str) {
char (*toReturn)[5] = malloc(sizeof *toReturn);
.. some operations here ..
return toReturn
}
我的 toReturn
包含字符串,例如 toReturn[0]
可能是 "Hello"
有什么建议吗?
最佳答案
据我了解,您想返回一个指针数组并为该数组的指针分配内存。使用您当前的代码,您不能返回指针数组,因为它是本地的。您可以通过以下方式进行:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char** loadValues () {
char** toReturn;
int i;
toReturn = malloc(5*sizeof(char*));
for(i=0;i<5;i++)
{
toReturn[i] = malloc(25); //Change the size as per your need
strncpy(toReturn[i], "string",i+1); //Something to copy
}
return toReturn;
}
int main()
{
int i;
char **arr = loadValues();
for(i=0;i<5;i++)
{
printf("%s\n", arr[i]);
}
for(i=0;i<5;i++)
{
free(arr[i]);
}
free(arr);
return 0;
}
注意 loadValues
的返回类型和为数组分配的内存在 main
中释放。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void loadValues (char **toReturn) {
int i;
for(i=0;i<5;i++)
{
toReturn[i] = malloc(25); //Change the size as per your need
strncpy(toReturn[i], "string",i+1); //Something to copy
}
}
int main()
{
int i;
char *arr[5];
loadValues(arr);
for(i=0;i<5;i++)
{
printf("%s\n", arr[i]);
}
for(i=0;i<5;i++)
{
free(arr[i]);
}
return 0;
}
您还应该检查对 malloc
的调用是否成功并处理错误。
关于c - 在 C 和 malloc 用法中返回一个 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14264979/