我有一个指向指针函数的指针,它接受两个参数,它应该返回指向数组的指针。但是在这种情况下返回指向数组的指针的正确方法是什么?这是我的代码:
#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;
}
返回表的正确方法是什么?就是我写的返回表;好的,还是应该像 return *table 甚至 return **table?而且,我需要释放 table 吗?
最佳答案
我想这就是你想要做的。
#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;
}
这可以做到,但您需要阅读更多内容以了解基础知识。
你的问题不是
how to return a pointer
而是如何使用 malloc
和 free
。
关于c - 指向指针函数的指针--->如何返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27458178/