【问题标题】:how to use dynamic stirng array in c如何在c中使用动态字符串数组
【发布时间】: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 缓冲区丢失。使用strcpystrdup

标签: c arrays dynamic


【解决方案1】:

你需要分配char *的大小-

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

要复制字符串,您需要使用strcpy。所以代替这个 -

word[i]=buff;          // 1

使用这个 -

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

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

【讨论】:

  • @kilowatt 很高兴它有所帮助。
猜你喜欢
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2014-06-20
  • 2015-02-26
  • 1970-01-01
  • 2017-08-27
  • 2019-04-18
  • 1970-01-01
相关资源
最近更新 更多