[英]Dynamic allocation of an array of pointers
我在 C 中的代碼有問題。我需要輸入一個用回車按鈕分隔的名稱列表。 當用戶輸入單詞“QUIT”時停止輸入。 程序需要按字母順序打印姓名列表(所有字母均為小寫)。
名稱的數量以及每個名稱的長度是未知的,需要動態分配。 此外,如果一個名稱在輸入中出現多次,則它在輸出中應該只出現一次。
這是代碼應該如何運行的示例:
Please enter a list of names:
john
chris
ben
chris
david
QUIT
有4個名字:
ben
chris
david
john
我想過使用動態分配的指針數組,其中每個指針包含每個名稱並且是動態分配的。 問題是我不知道如何在沒有運行時錯誤的情況下編寫它。
注意:在這一點上,我不允許使用我還沒有學到的東西,比如結構和遞歸,並且只能使用庫 stdio.h、stdlib.h 和 string.h。
提前致謝。
這是代碼(它不完整,但此時我收到運行時錯誤):
char **nameList;
int i = 0, j = 0, size = 0, check = 0;
printf("Please enter list of names:\n");
//allocate one cell of memory to the list
nameList = (char**)malloc(sizeof(char));
if (nameList == NULL)
{
printf("Cannot allocate Memory");
return 0;
}
//Add the first letter to the first string in the array
nameList[i][j] = getchar();
size += sizeof(char);
while (check != 1)
{
//check if current entered letter is not an enter
while (nameList[i][j] != '\n')
{
//allocated another char sized memory to the string
nameList = (char**)realloc(nameList, (size + sizeof(char)));
if (nameList == NULL)
{
printf("Cannot allocate Memory");
return 0;
}
j++;
//adding another char to the current string
nameList[i][j] = getchar();
size += sizeof(char);
}
j = 0;
if (nameList[i][j] == 'Q')
{
if (nameList[i][j + 1] == 'U')
if (nameList[i][j + 2] == 'I')
if (nameList[i][j + 3] == 'T')
check++;
}
i++;
}
nameList = (char**)realloc(nameList, (size + sizeof(char)));
嗯......你為什么在那里使用'+'? 而且您也在尋找錯誤類型的值的大小。
這將分配一個指針數組。 但是這里指向的指針是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.