简体   繁体   中英

Return an array of char in C and malloc usage

First attempt:

char* loadValues (char* str) {

  char* toReturn[5];

  .. some operations here ..

  return toReturn

}

This will obviously return warnings and will not work properly since the memory location is going to be free-d after the function is finished.

So I thought of using malloc, however, I don't understand how this may work with arrays.

Second attempt:

char* loadValues (char* str) {

  char (*toReturn)[5] = malloc(sizeof *toReturn);

  .. some operations here ..

  return toReturn

}

my toReturn contains strings, for example toReturn[0] may be "Hello"

Any suggestion?

As far as I understand, you want to return an array of pointers and allocate memory for the pointees of that array. With your current code, you can't return the array of pointers as it's local. You can do it in the following way:

#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;  
}

Notice the return type of loadValues and memory allocated for the array is freed in 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;  
}

You should also check if calls to malloc succeeded and handle errors.

malloc simply works by allocating a chunk of memory and returning a pointer to the beginning. What might be tricky here is that the array you're making doesn't contain characters, it contains pointers to characters, which means you can't simply say

char* toReturn[5] = malloc(memory);

As far as I can see you'd need to malloc enough memory for five char pointers for toReturn, then go through the elements and malloc however much memory you think you'll need to them. Take extra care you remember to go through the array again and free all the memory when you're done with it, before freeing the array itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM