【发布时间】:2017-04-24 03:41:29
【问题描述】:
我希望将 n 个单词存储到一个数组中。我在下面的代码中使用了指针来做到这一点。但问题是一旦读取了所有单词,这些单词就无法打印。
请提供任何解决方案。
#include <stdio.h>
#include <stdlib.h>
int main() {
char buff[10];
int i,T;
printf("Enter the no.of words:");
scanf("%d",&T);
char **word= malloc(10*T);
printf("Enter the words:\n");
for(i=0;i<T ;i++){
scanf("%s",buff);
word[i]= malloc(sizeof(char)*10);
word[i]=buff;
printf("u entered %s\n",word[i]);
if(i>0)
printf("u entered %s\n",word[i-1]);
}
printf("Entered words are:\n");
for(i=0;i<T ;i++)
printf("%s\n",word[i]);
}
【问题讨论】:
-
问题是你存储 same
buff指向每个数组元素的指针。这显然意味着它们都包含相同的值,并且还会导致内存泄漏,因为malloc缓冲区丢失。使用strcpy或strdup。