Reputation: 49
I have this pointer to pointer function that takes two arguments and it is suppose to return pointer to the array. But what is the proper way to return pointer to the array in this case? Here is my code:
#include <stdio.h>
#include <stdlib.h>
int **multiTable (unsigned int xs, unsigned int ys)
{
unsigned int i, j;
int **table = malloc( ys * sizeof(*table));
// should I put malloc(ys * xs * sizeof(*table))?
for(i = 0; i < ys; i++)
{
for(j = 0; j < xs; j++)
{
table[i][j] = (j+1) * (i+1);
}
}
return table; //what would be the proper way to return table? Is this ok?
free(**table); //by the way, do I need this?
}
int main()
{
int sum = 0;
sum = multiTable2(3,2);
return 0;
}
what would be the proper way to return table? Is what I written the return table; ok or should it be like return *table or even return **table? And also, do I need to free the table?
Upvotes: 2
Views: 83
Reputation: 19375
If I would like to use only one malloc, would this work: int (*table)[xs] = malloc(ys * sizeof(*table))
Yes, it would, if you adjust the function according to Matt McNabb's comment:
#include <stdio.h>
#include <stdlib.h>
int (*multiTable(unsigned int xs, unsigned int ys))[]
{
unsigned int i, j;
int (*table)[xs] = malloc(ys * sizeof *table);
for (i = 0; i < ys; i++)
for (j = 0; j < xs; j++)
table[i][j] = (j+1) * (i+1);
return table;
}
int main()
{
const int xs = 3, ys = 2;
int (*sum)[xs];
sum = multiTable(xs, ys);
int i, j;
for (i = 0; i < ys; i++, puts(""))
for (j = 0; j < xs; j++)
printf("%d", sum[i][j]);
return 0;
}
Upvotes: 0
Reputation: 53006
I think this is what you are trying to do.
#include <stdio.h>
#include <stdlib.h>
int **multiTable(unsigned int xs, unsigned int ys)
{
unsigned int i, j;
int **table;
table = malloc(ys * sizeof(int *)); /* you need space for ys integer arrays */
if (table == NULL)
return NULL;
for (i = 0 ; i < ys ; i++)
{
table[i] = malloc(xs * sizeof(int)); /* you need space for xs integers */
if (table[i] != NULL) /* did malloc succeed? */
{
for (j = 0 ; j < xs ; j++)
table[i][j] = (j + 1) * (i + 1);
}
}
return table;
}
int main()
{
int **sum;
sum = multiTable(3, 2);
/* do somenthing with sum here */
if (sum != NULL)
{
/* now you must use free, like this */
unsigned int i;
for (i = 0 ; i < 2 ; i++)
{
if (sum[i] != NULL)
free(sum[i]);
}
free(sum);
}
return 0;
}
this could be done, but you need to read more to understand the basics.
Your problem is not
how to return a pointer
but instead how to use malloc
and free
.
Upvotes: 1