gpt4 book ai didi

c - 如何在c中使用动态字符串数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:53 24 4
gpt4 key购买 nike

我想将 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]);


}

最佳答案

您需要分配 char * 的大小 -

char **word= malloc(sizeof(char *)*T); 

要复制字符串,您需要使用 strcpy。所以而不是这个 -

word[i]=buff;          // 1

使用这个-

strcpy(word[i],buff);         // include string.h header

通过 1.,您使用指针指向 buff,但存储在 buff 中的值发生了变化。所以所有指针指向的值都是相同的,你得到所有相同的输出,即存储在 buff 中的最新值。

关于c - 如何在c中使用动态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43579433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com