如何通过 malloc 分配并打印字符数组?

How to allocate by malloc and print arrays of characters?

我需要按 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;
}

我在打印这些字符串时遇到了问题。不知道怎么弄。

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

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

您需要像这样更改您的代码

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

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

也就是说,

  • 在使用 returned 指针之前,始终检查 malloc() 和家族的 return 值是否成功。
  • 无需在 C 中转换 malloc() 和家族的 return 值
  • sizeof(char) 在 C 中定义为 1。不需要乘以它的大小。
  • 除了使用 malloc()strcpy(),您还可以考虑使用 strdup() 来获得相同的结果。
#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;
}