c - 九九乘法表问题

标签 c malloc multiplication calloc

我正在尝试编写一个 C 函数来存储 0-x 范围内的乘法表。我编写的函数有一个错误,它只存储表的前 2 行或 3 行,并且该函数也从不返回值,我很困惑,不胜感激。

void makeTable (int x) {
int** table = malloc(x * sizeof(int*));
int i;
int q;
int* ptr;
for(i = 0; i <= x; i++){
    ptr = calloc(x, sizeof(int));
    for(q = 0; q <= x; q++){
        ptr[q] = (i * q);
    }
    table[i] = ptr;
}
return table;

}

最佳答案

在这里您访问尚未分配的内存。这是未定义的行为。

正确的做法是考虑 x 元素而不是 x+1

for(q = 0; q < x; q++){
        ptr[q] = (i * q);

外循环也是如此。

for(i = 0; i < x; i++){

还有其他一些事情 - 从声明为 void(未定义行为)的函数返回。不检查 malloccalloc 的返回值是有问题的。

所以编写函数的正确方法是

int** makeTable (int x) {
    int** table = malloc(x * sizeof *table);
    if(!table)
    {
        fprintf(stderr,"Error in mem alloc");
        exit(1);
    }
    for(size_t i = 0; i < x; i++){
        int * ptr = calloc(x, sizeof *ptr);
        if(!ptr)
        {
           fprintf(stderr,"Error in mem alloc");
           exit(1);
        }
        for(size_t q = 0; q < x; q++){
            ptr[q] = (i * q);
        }
        table[i] = ptr;
    }
    return table;
}

此外,您还应该在此程序中的某个位置添加逻辑,以使用 free 释放所有这些动态分配的内存。

关于c - 九九乘法表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441494/

相关文章:

C - 带有函数内 malloc 的 typedef 结构的动态数组

bit-manipulation - 如何使用按位运算符执行乘法?

jquery - 如何计算每一行的乘法并用jquery显示

c - 在普通 C 中可以/不能完成哪些特定于嵌入式 C 的事情

在 C 中创建唯一的订单 ID

c++ - Windows 怎么知道我没有使用内存?

c++ - C++ 中的重载运算符 - 编译但崩溃

在Windows和Linux下将UTF-16转换为UTF-8,在C中

c - 如何从 C 中的调用函数中释放局部变量分配的内存?

无法释放内存