如果你想在C中填充一个矩阵,你可以使用索引,像这样:
#include<stdio.h>
int main(){
char m[20][30];
int i = 0;
int j = 0;
while(i <= 20){
j=0;
while(j <= 30){
m[i][j] = 's';
printf("%c", m[i][j]);
j++;
}
printf("\n");
i++;
}
}
但是我怎样才能用指针做到这一点呢?
最佳答案
在你的情况下:
使用指针:
char m[20][30];
char *ptr; // Your pointer
ptr=m; // point ptr to the location where m points to
现在,替换
m[i][j] = 's';
printf("%c", m[i][j]);
与
*((char *)ptr + (i * 30) + j) = 's';
printf("%c", *((char *)ptr + (i * 30) + j));
为什么这有效?
对于一维数组:
int a[10];
您可以像这样访问它:
a[1]; //Say the 2nd element
因此,就指针而言,这相当于:
*((int*)a+1).
对于二维数组:
int b[NO_OF_ROWS][NO_OF_COLUMNS];
在一般形式中,假设任何元素:
b[r][c]; // let r < NO_OF_ROWS, c < NO_OF_COLUMNS be any index
相当于
*((int *)b + r * NO_OF_COLUMNS + c);
关于c - 使用指针在 C 中填充多数组(矩阵),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121973/