[英]Change a dynamic 2D char array through a function in C?
我正在創建此示例運行,以便可以更好地理解如何通過其他函數編輯動態數組,但是一旦添加了輔助函數,我便開始遇到段錯誤。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void other_side(char ***funk);
int main()
{
int i;
char *argv[11] = {"fish", "dish", "lags", "fags", "shag", "cool", "bean", "rekt", "noon", "coon", "lolz"};
char **yep, **nop;
yep = malloc(10 * sizeof *yep);
if(!yep) { // <-----------------added check for malloc error
printf("Error: failure to allocate memory\n");
exit(1);
}
printf("10 times %lu\n\n", sizeof *yep);
for(i = 0; i<10; i++) {
yep[i] = strdup(argv[i]);
printf("%s is in yep.\n", *(yep+i));
}
nop = realloc(yep, 11 * sizeof *yep); //you reallocate to the new total size.
if(nop == NULL) {
printf("Error: failure to allocate memory\n")
exit(1);
}
yep = nop;
*(yep+10) = strdup(argv[10]);
printf("Last but certainly not least, %s is in yep.\n", *(yep+10));
printf("Now to send yep over to the other side and have its values changed.\n");
other_side(&yep);
printf("Did it change?\n\n");
for(i=0; i<11; i++)
printf("%s is in yep.\n", *(yep+i));
for(i=0; i<11; i++) { //issue fixed when added strdup() above, previously static
free(*(yep+i));
}
free(yep);
return 0;
}
void other_side(char ***funk)
{
char *arr[11] = {"dude","yeah","gnar","nice","epic","need","more", "word","four","this","test"};
int i;
for(i=0; i<11; i++) {
**(funk+i) = strdup(arr[i]); //added strdup() here as well
printf("%s is currently in yep.\n", **(funk+i));
}
printf("\n");
}
我注意到的幾件事是,當我嘗試將main的第11個內存塊釋放到數組中時,Valgrind注意到了不必要的釋放。 我不確定這是否是我的問題,但我也注意到該函數只會在導致分段錯誤之前更改兩個單詞。
編輯說明:自編輯以來,我仍然遇到段錯誤,但是valgrind對正在發生的事情更加清楚。 (對位於地址0x400B18的映射區域的錯誤權限)
您關於運算符的優先順序很重要,並且您錯過了兩個括號以確保操作正確。 這: **(funk+i)
意思是: *(funk[i])
,而不是您想要的(*funk)[i]
。
這個:
**(funk+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", **(funk+i));
應該是這樣的:
*((*funk)+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", *((*funk)+i));
坦率地說,它很容易理解為:
(*funk)[i] = strdup(arr[i]);
printf("%s is currently in yep.\n", (*funk)[i]);
我將其余的內存管理留給您解決。 (即,您在上述循環代碼中覆蓋的所有指針所指向的動態內存泄漏)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.