1. 程式人生 > >二維char陣列與二維char指標

二維char陣列與二維char指標

char**的記憶體結構可以看成有多個連續的char*型別的元素構成,而二維字元陣列是由M*N個字元組成。


1. 以下函式將出現段錯誤:
#include <stdio.h>
#define M 2
#define N 100


void test(const char** pstr)
{
int i = 0;
for(i = 0; i < 2; i++)
{
printf("array[%d]= %s/n",  i,*(pstr+i));
}
return;
}


int main()
{
char char_array[M][N] = {"a.txt", "b.txt"};

test((const char**) char_array);


return 0;
}


原因:
用char**傳遞二維字串陣列的首地址時。相同的地址空間,但由於元素型別不一樣,取出的值也不一樣。
使用*pstr時,實際上取出的是前4個字元組成的int值,不是期望中的char_array[0]的起始地址。所以出現段錯誤也就很好理解了。


2. 二維陣列和二維指標的sizeof用法
char char_array[3][10] = {"a.txt", "b.txt"};
printf("char_array's sizeof = %d\n", sizeof(char_array));
printf("*char_array's sizeof = %d\n", sizeof(*char_array));
printf("**char_array's sizeof = %d\n", sizeof(**char_array));


char **char_array2 = {"a.txt", "b.txt"};
printf("char_array2's sizeof = %d\n", sizeof(char_array2));
printf("*char_array2's sizeof = %d\n", sizeof(*char_array2));
printf("**char_array2's sizeof = %d\n", sizeof(**char_array2));


列印結果為:
char_array's sizeof = 30
*char_array's sizeof = 10
**char_array's sizeof = 1
char_array2's sizeof = 4
*char_array2's sizeof = 4
**char_array2's sizeof = 1

3. 二維陣列和二維指標的賦值問題
char *str2 [20]={"helloworld","example"};
char **p2 = str2;//可以正確列印
int y;
for(y = 0;y < 2; y++){
printf("p2 = %s\n", p2[y]);
}


char str1[16][20]={"helloworld","example"};
char **p1 = str1;//像這樣是錯誤的, 出現記憶體錯誤
int z;
for(z = 0;z < 2; z++){
printf("p1 = %s\n", p1[z]);
}