wrmlovezsj 2021-11-16 11:07 采纳率: 100%
浏览 70
已结题

这种情况往指针数组里存用户输入的字符串gets怎么用呢,或者更好的方法。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define N 20
int main()
{
    int n,i;
    printf("Please input an integer:");
    scanf("%d",&n);
    char (*ptr)[N]=NULL;
    (char*)malloc(sizeof(char)*n);
    printf("Please input %d strings:",n);
    for(i=0;i<n;i++){
    gets(*ptr);
    }
    printf("%s",&ptr[0][0]);
    free(ptr);
}

  • 写回答

1条回答 默认 最新

  • 关注

    代码修改如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    #define N 20
    int main()
    {
        int n,i;
        printf("Please input an integer:");
        scanf("%d",&n);
        char *ptr[N];//=NULL;
        
        printf("Please input %d strings:",n);
        for(i=0;i<n;i++){
            ptr[i] = (char*)malloc(200);//200这个数根据情况调整一下大小
            gets(ptr[i]);
        }
        //输出
        for(i=0;i<n;i++)
            printf("%s\n",ptr[i]);
    
        for(i=0;i<n;i++)
        {
            free(ptr[i]);
            ptr[i] = 0;
        }
        
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月24日
  • 已采纳回答 11月16日
  • 创建了问题 11月16日