【问题标题】:How to allocate by malloc and print arrays of characters?如何通过 malloc 分配和打印字符数组?
【发布时间】:2015-12-19 17:15:48
【问题描述】:

我需要通过malloc() 分配字符数组,然后打印出来。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main (void){
    int i, n, l;
    char **p;
    char bufor[100];
    printf("Number of strings: ");
    scanf("%d", &n);
    p=(char**)malloc(n*sizeof(char*));
    getchar();
    for (i=0; i<n; ++i){
        printf("Enter %d. string: ", i+1);
        fgets(bufor, 100, stdin);
        l=strlen(bufor)+1;
        *p=(char*)malloc(l*sizeof(char));
        strcpy(*p, bufor);
    }
    for (i=0; i<n; ++i){
        printf("%d. string is: %s", i+1, *(p+i));
    }

    return 0;
}

我在打印这些字符串时遇到了问题。我不知道如何获得它们。

【问题讨论】:

标签: c arrays pointers char malloc


【解决方案1】:

如我所见,问题在于您一遍又一遍地覆盖同一个位置。这边

  1. 您正在丢失之前分配的内存。
  2. 只保留最后一个条目。

你需要改变你的代码

    p[i]=malloc(l);
    strcpy(p[i], bufor);

在循环中使用下一个指向指针的指针。

也就是说,

  • 在使用返回的指针之前,请务必检查malloc() 和family 的返回值是否成功。
  • 无需在C中强制转换malloc()和family的返回值。
  • sizeof(char) 在 C 中定义为 1。不需要乘以它的大小。
  • 除了使用malloc()strcpy(),您还可以考虑使用strdup() 来达到相同的效果。

【讨论】:

  • 感谢您的回答。它现在正在工作。顺便提一句。我在 stackoverflow 的某个地方读到 sizeof(char) 是一种风格问题,通常应该写出来。
  • imo,不应将使用 sizeof(char) 替换为 1(或无),因为包含它会使操作变得明确,从而使其他人更容易理解您的代码。尤其是在您执行重要且具有潜在危险的操作(例如内存分配)的地方。
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   char  *names[6] ;
   char n[50] ;
   int  len, i,l=0 ;
   char *p ;
   for ( i = 0 ; i <= 5 ; i++ )
    {
         printf ( "\nEnter name " ) ;
         scanf ( "%s", n ) ;
         len = strlen ( n ) ;
         p = malloc ( len + 1 ) ;
         strcpy ( p, n ) ;
         names[i] = p ;
         if (l<len)
         l=len;
    }


     for ( i = 0 ; i <= 5 ; i++ )
    printf ( "\n%s", names[i] ) ;
    printf("\n MAXIMUM LENGTH\n%d",l);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2012-03-24
    • 1970-01-01
    • 2012-08-10
    • 2021-05-31
    • 2021-11-29
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多