这是我的源代码,这是不言自明的,我希望在这里得到一些帮助。一切都适用于 matrix1 ,但 matrix2 循环中的代码会产生错误。 *(matrix1+i)
和*matrix1[i]
之间有什么区别?我没有看到任何=(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void example(){
int i;
int qty = 5;
char **matrix1 = (char**)malloc(qty*sizeof(char));//matrix example(1)
char **matrix2 = (char**)malloc(qty*sizeof(char));//matrix example(2)
for(i=0;i<qty;i++){
//Why the heck may i allocate each vector in this way:
*(matrix1+i) = (char*)malloc(100*sizeof(char));
//...but not in this way(the code below generates an error):
*matrix2[i] = (char*)malloc(100*sizeof(char));
//And why the heck may i use strcpy this way:
strcpy(*(matrix1+i),"some string");
//...but not in this way(the code below generates an error):
strcpy(*matrix2[i],"some string");
}
}
int main(void){
example();
getch();
return 0;
}
答案 0 :(得分:3)
*(matrix1+i)
是指向2维数组i
中索引为char** matrix1
的行的指针,其类型为char*
。但*matrix2[i]
是索引为i
的行的第一个元素,其类型为char
。
虽然*(matrix1+i)
与matrix1[i]
相同,但*matrix2[i]
与**(matrix2+i)
相同。
像这样调整你的代码:
char **matrix1 = (char**)malloc(qty*sizeof(char));//matrix example(1)
char **matrix2 = (char**)malloc(qty*sizeof(char));//matrix example(2)
for(i=0;i<qty;i++){
*(matrix1+i) = (char*)malloc(100*sizeof(char));
matrix2[i] = (char*)malloc(100*sizeof(char));
....
}
答案 1 :(得分:2)
*(matrix1+i)
相当于matrix1[i]
,类型为char *
,而*matrix2[i]
取消引用指针matrix1[i]
,类型为char
答案 2 :(得分:2)
a[b]
与*(a+b)
相同。
因此*(matrix1+i)
和*matrix1[i]
之间的差异是*
s的数量:
[]
语法后面)。