Re: [問題] function中傳入指標型態問題
我寫了好久,最後全刪掉。
該補的是幾個重點
#define N 2
#define LEN 10
void func1(char *p[LEN])
{
for(int i=0; i!=N; ++i)
puts(p[i]);
}
實際上進去的時候, char *p[LEN] 是看做 char** p, 所以用
char *str_arr_p[LEN] = {"aa", "bb"};
char str_2dim[N][LEN] = {"aa", "bb"};
char **str_heap = (char**)malloc(sizeof(char*)*N);
/* initialize for str_heap */
func1(str_arr_p);
func1(str_heap);
這兩個都可過。但若是用
char buf[N][LEN];
func1(buf);
這不會過, 最後會死在 (隱含呼叫 strlen.asm) 裡面。
------
吊脆的地方又在於若非以 C-style 方式去傳
void funci1(int *ptr[LEN])
{
int i, j;
for(i=0; i!=N; ++i) {
for(j=0; j!=LEN; ++j)
printf("%d ", ptr[i][j]);
putchar('\n');
}
}
上面的 int* ptr[LEN] 還是看做 int**
int *int_arr_p[LEN] = {1, 2};
int int_2dim[N][LEN] = {1,2};
int **int_heap = (int**)malloc(sizeof(int)*N);
/* init for int_heap */
最後,這裡只有 int_heap 會過,這是我認為 C-Style String 吊脆的地方。
-----
我只是想表達,C 語言在探討 pointer / array 時,
string 部份最後全都拉出來做差別式的思考,
我看到很多特例在裡面。
--
YouLoveMe() ? LetItBe() : LetMeFree();
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 180.177.78.41
推
09/10 00:42, , 1F
09/10 00:42, 1F
→
09/10 00:43, , 2F
09/10 00:43, 2F
推
09/10 00:44, , 3F
09/10 00:44, 3F
→
09/10 00:44, , 4F
09/10 00:44, 4F
→
09/10 00:44, , 5F
09/10 00:44, 5F
推
09/10 00:46, , 6F
09/10 00:46, 6F
→
09/10 00:47, , 7F
09/10 00:47, 7F
→
09/10 00:48, , 8F
09/10 00:48, 8F
→
09/10 00:48, , 9F
09/10 00:48, 9F
→
09/10 00:48, , 10F
09/10 00:48, 10F
→
09/10 00:49, , 11F
09/10 00:49, 11F
→
09/10 01:00, , 12F
09/10 01:00, 12F
推
09/10 01:00, , 13F
09/10 01:00, 13F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):