我從螢屏上一個一個地輸入單詞并將它們發送到一個陣列。當然,我可以立即為陣列分配大記憶體,但我想為此動態分配記憶體。
例如我有一個陣列words。首先,我為其分配了一點記憶體,char *words = malloc(capacity)例如容量 = 15。...輸入螢屏上的單詞... 所有分配的記憶體都已滿,我為進一步的作業分配了更多記憶體char *tmp = realloc(words, capacity*2)。可能,我明白它是如何作業的。但是我不知道怎么寫。即如何輸入這些單詞并將它們發送到一個陣列。你能詳細描述我應該怎么做嗎?
例子:
我從螢屏上輸入單詞,side left ball rich最后我有一個陣列*arr = ["side", "left", "ball", "rich"]
uj5u.com熱心網友回復:
您需要有一組指標,每個索引都存盤一個單詞。還必須注意釋放記憶體。
片段如下,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int size = 3;
char word[30];
char **word_list = malloc(sizeof(word_list) * size);
printf("Enter %d Words\n",size);
for(int i =0; i<size; i){
scanf("0s",word);
int word_size = strlen(word) 1;
word_list[i] = malloc(word_size);
strncpy(word_list[i],word,word_size);
}
printf("\nEntered words are\n");
for(int i=0; i<size; i){
printf("%s ",word_list[i]);
}
//resizing the capacity of the array
{
int resize;
printf("\nresize array size to: ");
scanf("%d",&resize);
if(size<resize){
for(int i=size-1; i>=resize; --i)
free(word_list[i]);
}
word_list = realloc(word_list, sizeof(word_list) * resize);
if(resize > size)
printf("Enter %d Words \n",resize-size);
for(int i =size; i<resize; i){
scanf("0s",word);
int word_size = strlen(word) 1;
word_list[i] = malloc(word_size);
strncpy(word_list[i],word,word_size);
}
size = resize;
}
printf("Current words are\n");
for(int i=0; i<size; i){
printf("%s ",word_list[i]);
}
//Memory deallocation
for(int i=0; i<size; i){
free(word_list[i]);
}
free(word_list);
return 0;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455483.html
