c - returning array of string from function not working as expected -


i trying pass array of strings function, make changes inside function, , pass main() , print see changes. not working expected. please tell me i'm going wrong.

#include <stdio.h> #include <string.h> #include <malloc.h>  //don't forget declare function char** fun(char [][20]);  int main(void) {     char strar[10][20] = { {"abc"}, {"def"}, {"ghi"}, {""},{""} }; //make sure 10 added     char** ret; //no need allocate ret, ret placeholder, allocation done in fun     int = 0;      ret = fun(strar);     for(i=0;i<4;i++)         printf("[%s] ",ret[i]);      printf("\n");     return 0; }  //don't forget function has return char** , not int. (remember char**, not char*) char** fun(char strar[][20]) {     int = 0;     char** ret;     ret = malloc(sizeof(void*)); //sizeof(void*) enough, has hold address       for(i=0;i<5;i++)     {         ret[i] = malloc(20 * sizeof(char));         strcpy(ret[i],strar[i]);     }      strcpy(ret[3],"fromfun");      return ret; } 

you need make sure allocate full array of pointers ret array.

//don't forget function has return char** , not int. (remember char**, not char*) char** fun(char strar[][20]) {  int = 0;  char** ret;  ret = malloc(sizeof(void*) * 5); //sizeof(void*) enough, has hold address    for(i=0;i<5;i++)  {   ret[i] = malloc(20 * sizeof(char));   strcpy(ret[i],strar[i]);  }   strcpy(ret[3],"fromfun");   return ret; } 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -