![](/img/trans.png)
[英]Both dynamic column and row sized 2D array updated in recursive function in c programming
[英]C: dynamic sized 2d array of strings
我對C還是很陌生,也為數組的內存分配和字符串存儲為字符數組而感到困惑。
我想用n行,2列和可變大小的字符串長度創建2d字符串數組。 所以它的結構看起來像這樣。
char people = {
{"name1..", "info.."},
{"name2..", "info.."},
{"name3..", "info.."},
}
我將n作為用戶輸入,因此我知道該數組將包含多少行。
當用戶使用realloc輸入類型時,如何使用malloc定義這樣的數組並調整為字符串分配的空間大小。 還是有更好的方法在C中存儲這樣的數據?
我希望能夠像這樣使用它:
printf("%s", people[0][0]);
prints: name1..
people[0][0][4] = 'E';
//Change the fifth letter of this element to for example E
我已經嘗試了很多事情,但是似乎沒有什么能像我想要的那樣工作。
使用指向char *
指針可以實現您的要求。
考慮以下示例作為參考。
char ***arr; // to hold n*2 strings
int n =3;
arr = malloc(n*sizeof(char **));
int i = 0;
for (i =0;i<n;i++)
{
arr[i] = malloc(2*sizeof (char *)); // to hold single row (2 strings)
arr[i][0] = malloc(10); // to hold 1st string
arr[i][1] = malloc(10); // to hold 2nd string
strcpy(arr[i][0],"name");
strcpy(arr[i][1],"info");
arr[i][0][4] = 'E'; // As you wished to change particular char
printf("%s %s", arr[i][0], arr[i][1]);
printf("\n");
}
為了調整特定字符串的大小,您可以使用realloc
,如下所示。
char *temp;
temp = realloc(arr[1][0], 100);
arr[1][0] = temp;
免責聲明:我尚未添加任何綁定和錯誤檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.