如何使用数组指针(int *)创建和打印这种二维数组:
0 1 2 3 4 5 6 7 8...
1 2 3 4 5 6 7 8 9...
2 3 4 5 6 7 8 9 10...
3 4 5 6 7 8 9 ...
4 5 6 7 8 9...
5...
我目前有这段代码:
#include <stdio.h>
#include <stdlib.h>
void createMatrix(int * matrix, int row, int column)
{
puts("Begin creating matrix.");
int i, j;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
*(matrix) = i + j;
matrix++;
}
}
puts("Success!");
}
int printMatrix(int * matrix, int row, int column)
{
puts("Begin printing matrix!");
int i, j, valuesPrinted;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
printf("%5d ", *(matrix + i * j));
valuesPrinted++;
}
puts("");
}
puts("Printing success!");
return valuesPrinted;
}
int main()
{
int row = 11;
int column = 13;
int * matrix = malloc(sizeof(int) * row * column);
createMatrix(matrix, row, column);
printMatrix(matrix, row, column);
return 0;
}
我想要做的是:使用declare数组并赋值给指针,然后将指针传递给函数并给它如上所述的值。我认为问题在于我通过指针初始化2D数组并访问它。
结果是:
0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9 10 11 12
0 2 4 6 8 10 12 2 4 6 8 10 12
0 3 6 9 12 3 6 9 12 3 6 9 12
0 4 8 12 4 8 12 4 8 12 4 8 12
0 5 10 3 8 13 6 11 4 9 14 7 12
0 6 12 6 12 6 12 6 12 6 12 6 12
0 7 2 9 4 11 6 13 8 15 10 17 12
0 8 4 12 8 4 12 8 16 12 8 16 12
0 9 6 3 12 9 6 15 12 9 18 15 12
0 10 8 6 4 14 12 10 8 18 16 14 12
答案 0 :(得分:2)
您的打印代码使用错误的表达式来访问矩阵的元素。你有:
printf("%5d ", *(matrix + i * j));
你需要:
printf("%5d ", *(matrix + i * column + j));
或者:
printf("%5d ", matrix[i * column + j]);
答案 1 :(得分:2)
int *matrix = malloc(sizeof(int) * row * column);
// could better be written as
int *matrix = malloc((row*column) * sizeof *matrix);
上述语句动态分配大小为row * column
的整数数组。如果要访问此数组的元素,就像访问2D数组的元素一样,则行i
和列j
的元素具有索引
i * column + j
将printMatrix
功能修改为 -
int printMatrix(int * matrix, int row, int column)
{
puts("Begin printing matrix!\n");
int i, j, valuesPrinted;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
// this is equivalent and more readabable
// printf("%5d ", matrix[i*column + j]);
printf("%5d ", *(matrix + i*column + j));
// ^ note i is multiplied by column
valuesPrinted++;
}
puts("");
}
puts("Printing success!\n");
return valuesPrinted;
}
答案 2 :(得分:1)
printf("%5d ", *(matrix + i * column + j));
而不是
printf("%5d ", *(matrix + i * j));