#define OK 0
#define MAXSTRING 200
#define NUMBER 10
#define MALLOC_ERROR 2
int main(int argc, char** argv) {
char **B = (char**)malloc(sizeof(char*)*NUMBER);
char buffer[MAXSTRING];
int i, strings = 0, arraysize = NUMBER;
if ((B = (char**)malloc(sizeof(char*)*NUMBER))==NULL) {
printf("initial malloc error\n");
fflush(stdout);
exit(MALLOC_ERROR);
}
for(int i = 0; i< NUMBER; i++) {
B[i] = (char*)malloc(sizeof(char)*MAXSTRING);
}
while((fgets(buffer,MAXSTRING,stdin))!=NULL) {
/*
if(strings+1>arraysize)
{
arraysize = 2*arraysize;
B=realloc(B,(arraysize)*sizeof(char*));
}
*/
buffer[strlen(buffer)-1]='\0';
B[strings] = buffer;
printf("%s \n", buffer);
strings++;
}
printf("Read %d strings:\n", strings);
for (i = 0; i<strings ; i++) {
printf("\t%s\t %d\n", B[i], (int)strlen(B[i]));
}
return 0;
}
當我試圖從循環打印B [i],它只輸出標準輸入的所有位置的最後輸入。我試着用普通的for循環進行測試,它以某種方式工作,但我不知道問題的原因。謝謝您的幫助!!例如,我把「長頸鹿」作爲第一個輸入,另一個輸入「吃」,最後輸入「離開」,B [i]的循環只輸出「離開」char陣列工作不正常,因爲它應該(C編程)
你是什麼輸入?你的輸出是什麼?你的_expected_輸出是什麼?請[編輯]你的問題,並明確說明。 –
非常感謝。它現在適用於strcpy。 :D再次感謝 –