I am trying to pass an array of strings to a function, make some changes to it inside this function, and pass it back to main() and print it to see the changes. It is not working as expected. Please tell me where I'm going wrong.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
//don't forget to declare this function
char** fun(char [][20]);
int main(void)
{
char strar[10][20] = { {"abc"}, {"def"}, {"ghi"}, {""},{""} }; //make sure 10 is added
char** ret; //no need to allocate anything for ret, ret is just a placeholder, allocation everything done in fun
int i = 0;
ret = fun(strar);
for(i=0;i<4;i++)
printf("[%s] ",ret[i]);
printf("\n");
return 0;
}
//don't forget function has to return char** and not int. (Remember char**, not char*)
char** fun(char strar[][20])
{
int i = 0;
char** ret;
ret = malloc(sizeof(void*)); //sizeof(void*) is enough, it just has to hold an address
for(i=0;i<5;i++)
{
ret[i] = malloc(20 * sizeof(char));
strcpy(ret[i],strar[i]);
}
strcpy(ret[3],"fromfun");
return ret;
}
void *without actual need. The correct way isret = malloc(sizeof(*ret)). This will infer the type from the variable, thus always have the correct size. The second bestret = malloc(sizeof(char *)). Note: I intentionally omitted the required multiplier. Also note:sizeof(char)is defined to yield1. I.e., it will never yield anything different, so it is nonsense to use.