c - 指向指针函数的指针--->如何返回指针

标签 c

我有一个指向指针函数的指针,它接受两个参数,它应该返回指向数组的指针。但是在这种情况下返回指向数组的指针的正确方法是什么?这是我的代码:

#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

而是如何使用 mallocfree

关于c - 指向指针函数的指针--->如何返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27458178/

相关文章:

c++ - 在哪里可以找到所有数学函数的描述,比如 floorf 和其他函数?

c - 链表行为 - 帮助我理解

c++ - 如何将长文档字符串放入 c/c++ 程序中?

c++ - 棘手的算术或手法?

c - 帮助弄清楚制作文件路径字符串

CTRL+D 不发送到管道 C

c - 写(): Bad file descriptor

c - Leetcode运行时错误

c - 使用两种不同的有符号整数二进制表示形式的程序

c - 与结构内仅一个成员进行 union 的目的