c - 包含多个表和一个 malloc() 的数组

标签 c malloc

所以,我要做的就是创建一个数组,其中包含数字 N 的多个表,即:

"Enter a number = 6"
"1 2 3 4 5 6"
"2 4 6 8 10 12" and so on untill 36

这是我的代码:

int * initiallizeArray(int * rows)
{
    int i = 0, j = 0;
    int * twoDArray = 0;
    printf("Enter a number: ");
    scanf("%d", rows);
    twoDArray = (int*)malloc(sizeof(int) * (*rows * *rows));
    for (i = 0; i < *rows; i++)
    {
        for (j = 0; j < *rows; j++)
        {
            //twoDArray[i * *rows + j] =
        }
    }
    return twoDArray;
}

带有“//”的行是我不知道要在其中实现什么 基本上它在整个数组中循环,但我不知道将什么放入特定单元格

最佳答案

由于 twoDArray 实际上不是一个二维数组,因此您最好将其重命名为更清晰的名称。不建议强制转换 malloc 的返回值,因为这是不必要的,并且如果更改要分配的指针的类型,可能会引入错误。 for 循环的主体非常简单:(i + 1) * (j + 1)

int* initiallizeArray(int* rows)
{
    int i = 0, j = 0;
    int* mult_table = NULL;
    printf("Enter a number: ");
    scanf("%d", rows);
    mult_table = malloc((sizeof *mult_table) * (*rows) * (*rows));
    for (i = 0; i < *rows; i++)
    {
        for (j = 0; j < *rows; j++)
        {
            mult_table[i * (*rows) + j] = (i + 1) * (j + 1);
        }
    }
    return mult_table;
}

关于c - 包含多个表和一个 malloc() 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43297629/

相关文章:

c - 当我尝试使用函数中通过引用传递的预分配矩阵读取值时出现段错误

c - malloc 问题?

c - 使用 strtok 转储的段错误核心

c - malloc() : memory corruption; Aborted (core dumped)

c - 为什么 malloc 不能与 strcpy 一起使用?

调用 sprintf 函数

C++ malloc 段错误

C _fullpath() 返回错误路径

c - C 中未使用的变量错误 .. 简单问题

c - 运行任何英特尔 AVX 函数后,数学函数需要更多周期