I want to pass an arrays index from my function to main. How can I do that? For example:
void randomfunction()
{
int i;
char k[20][10];
for (i=0;i<20;i++)
strcpy(k[i], "BA");
}
int main(int argc, char *argv[])
{
int i; for (i=0;i<20;i++) printf("%s",k[i]);
return 0;
}
I know that for you this is very simple but I've found similar topics and they were too complicated for me. I just want to pass the k array to main. Of course my purpose is not to fill it with "BA" strings...
You want to allocate the memory dynamically. Like this:
char** randomfunction() {
char **k=malloc(sizeof(char*)*20);
int i;
for (i=0;i<20;i++)
k[i]=malloc(sizeof(char)*10);
//populate the array
return k;
}
int main() {
char** arr;
int i;
arr=randomfunction();
//do you job
//now de-allocate the array
for (i=0;i<20;i++)
free(arr[i]);
free(arr);
return 0;
}
Here is another option. This works because struct
s can be copied around , unlike arrays.
typedef struct
{
char arr[20][10];
} MyArray;
MyArray random_function(void)
{
MyArray k;
for (i=0;i<sizeof k.arr / sizeof k.arr[0];i++)
strcpy(k.arr[i], "BA");
return k;
}
int main()
{
MyArray k = random_function();
}
Simplest way:
void randomfunction(char k[][10])
{
// do stuff
}
int main()
{
char arr[20][10];
randomfunction(arr);
}
If randomfunction
needs to know the dimension 20
, you can pass it as another argument. (It doesn't work to put it in the []
, for historial reasons).
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.