我有以下C代碼,其工作原理:如何通過指針的指針的陣列用C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int pw = sizeof(char*); // width of pointer (to char)
int num;
int first = 1;
int size = 0;
int incr = 10;
char *(*arr)[]; // pointer to array of pointers to char */
test(char* s, int i)
{
int j;
char *(*newarr)[]; // pointer to array of pointers to char
if (first) { // first time
arr = malloc(pw*incr); // malloc array
first = 0; // skip from now on
size = incr; // save the size
}
if (i >= size) { // out of space
newarr = malloc(pw*(size+incr)); // get incr bigger space
for (j=0; j<size; j++) // copy the elements from the old
(*newarr)[j] = (*arr)[j]; // array to new array
free(arr); // free the old array space
arr = newarr; // point old array to new array
size = size+incr;
};
int len = strlen(s); // length of s
(*arr)[i] = malloc(len+1); // assign pointer to pointer array element
strcpy((*arr)[i], s); // copy s to array
// both arguments must be pointers
printf("%d\t%s\n", i, (*arr)[i]);
};
main()
{
char* s = "this is a string";
for (num=0; num<30; num++) // add 30 pointers to s to *arr
test(s, num);
for (num=0; num<30; num++)
printf("%d\t%s\n", num, (*arr)[num]); // print out what they point to
};
它打印出「I \ t這是一個字符串」爲「i」的從0到29的兩倍。我想要做的是從文件頂部傳遞'arr'作爲'test'的參數。我想這樣做的原因是因爲我想傳遞幾個不同的數組,所有這些數組都被聲明爲相同的方式。如果我做最小的改動要做到這一點,我得到:
0 this is a string
Segmentation fault (core dumped)
這裏是diff命令的輸出,顯示最小的變化:
13c13
< char *(*arr)[]; // pointer to array of pointers to char */
---
> char *(*jarr)[]; // pointer to array of pointers to char */
15c15
< test(char* s, int i)
---
> test(char* s, int i, char *(*arr)[])
52c52
< test(s, num);
---
> test(s, num, jarr);
54,55d53
< for (num=0; num<30; num++)
< printf("%d\t%s\n", num, (*arr)[num]); // print out what they point to
換句話說一切都只是重命名相同'arr'作爲'jarr'並傳遞給'test'。
由於提前, 邁克
當您遇到分段錯誤或任何其他崩潰時,您的第一反應應該是在調試器中運行您的程序。它會幫助你找到崩潰的位置,並且讓你檢查可能導致崩潰的變量。 –
謝謝你。我應該說它崩潰在''(* arr)[i] = malloc(len + 1); //在第二次通過時將指針指向指針數組元素'。 – user1625815
看起來你正在使這種方式比它需要更復雜 - 爲什麼不使用'char **'並按照通常的方式分配內存呢? –