使用2D int fill函数抛出错误

时间:2013-12-01 10:09:52

标签: c casting tabs int return

我遇到了一些问题,我需要填写一个2D整数标签,所以我做了这个功能:

int **ft_fill_tab(void) {
    int **res;
    int row;
    int col;

    // creating a 15 cols by 10 rows TAB
    res = (int **)malloc(sizeof(int *) * 10);
    res[0] = (int *)malloc(sizeof(int) * 2);
    res[0][1] = 15;
    res[0][2] = 10;
    row = 1;
    col = 0;
    while (row < res[0][1])
    {
        res[row] = (int*)malloc(sizeof(int) * res[0][1]);
        while (col <= res[0][0])
        {
            res[row][col] = 0;
            col++;
        }
        row++;
        col = 1;
    }
    return (res);
}

...我在main.c中使用/调用这样:

int main (void) {
    // ...
    int **tab_test;
    tab_test = ft_fill_tab();
    // ...
    return (0);
}

当我试图编译我的程序时,gcc对我说: 警告:赋值从整数中生成指针而不进行强制转换 (main.c,在ft_fill_tab();调用行)

我也试图以任何方式(即使在主文件中)转换我的函数的返回值,但我无法理解这个错误出现的位置。

......有什么想法吗? 谢谢你的未来!

1 个答案:

答案 0 :(得分:3)

不应该这个

res[0][1] = 15;
res[0][2] = 10;

res[0][0] = 15;
res[0][1] = 10;

在我的对称感的带领下,你的代码看起来像这样:

// creating a 15 cols by 10 rows TAB
int ** res = malloc(sizeof(int *) * 10);
res[0] = malloc(sizeof(int) * 2);

res[0][0] = 15;
res[0][1] = 10;

{
  int row = 1;
  while (row < res[0][1])
  {
    int col = 1;

    res[row] = malloc(sizeof(int) * res[0][0]);    
    while (col < res[0][0])
    {
        res[row][col] = 0;
        col++;
    }

    row++;
  }
}

顺便说一下,我假设您为了便于阅读而遗漏了对malloc()的调用的错误检查。


参考您引用的错误消息:

看起来main()试图在不知道任何相关信息的情况下调用int **ft_fill_tab(void),可能是因为它是在代码中main()之后定义的。因此编译器假定int **ft_fill_tab(void)返回默认值int

然后编译器尝试分配给int ** tab_test,这会导致您得到错误。

要解决此问题,请在使用之前添加int **ft_fill_tab(void)的原型,此处main()之前:

#include <stdlib.h> /* for malloc at least */

int **ft_fill_tab(void);

int main(void)
{
  ...
  int **tab_test = ft_fill_tab();
  // ...
  return (0);
}

int **ft_fill_tab(void)
{
  ...
}
相关问题