c - 在 C 和 malloc 用法中返回一个 char 数组

标签 c

第一次尝试:

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/

相关文章:

c - 在这个字符串比较函数中对 (const char*) cast C 的剖析和解释

C - pthreads 似乎只使用一个核心

c++ - 如何用按位运算实现位 vector ?

C - 使用 fork() 创建 3 个子进程

c - 关于指针的奇怪的事情

c - 如何创建一个节点,然后将其添加到链表中?

c - 将字符串拆分为C中的单词数组

无法从链表中删除第一个节点

c - 如何从原始套接字获取 IP src addr

c - malloc - 系统调用 - 它是如何制作的?