c - 使用 scanf 接受字符串并使用 printf 显示它们

标签 c

<分区>

我无法使用 printf 检索字符串。而不是收到错误:段错误

int main(){

        char * a[5];
        int i;

        printf("\n enter value ");

        for (i=0;i<5;i++){
                printf("%d Name :\n",i);
                scanf("%s",&a[i]);
        }

        printf("%s",a[2]);
        printf("%s",a[3]);

}
~     

最佳答案

char * a[5];5 字符指针数组,这意味着您可以存储任意长度的 5 字符缓冲区。 问题出在声明中 scanf("%s",&a[i]); 将其替换为 scanf("%s",a[i]);

案例 1:-

int main(){
        char *a[5] = {"stackoverflow","meta","ask ubuntu","super","unix"};
        /* here a[row] can have any number of char */
        for (int i = 0 ;i < 5;i++) {
                printf("%s\n",a[i]);
        }
        return 0;
}

案例 2:-

int main(){
        char *a[5];
        for (int i=0;i<5;i++){
            printf("%d Name :\n",i);
            a[i] = malloc(MAX);/* define MAX how many char you want to store into that */
            scanf("%s",a[i]); /* & not required as a[i] itself address */
        }
        for (int i = 0 ;i < 5;i++) {
                printf("%s\n",a[i]);
        }
        /* don't forget to free once job is done */
        for (int i = 0 ;i < 5;i++) {
                free(a[i]);
        }
        return 0;
}

关于c - 使用 scanf 接受字符串并使用 printf 显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49815014/

相关文章:

c - 在不同网络命名空间中的进程之间共享状态

c - 具有请求超时的 libevent http 客户端

c - C 中的命名空间库

c - 如何将MPU6050设备数据发送到IoT Hub

java - 编译静态链接的 netty-tcnative 失败,与来自 JDK 的 jni.h 不匹配

c - 在函数之间传递结构数组

c - 即使提供的种子相同,为什么 openssl 给出不同的随机数?

c - 使用结构将一个文件中的结果写入另一个文件中?

c - 带有 EOF 的 getchar() 未按预期运行

c - 关于我在网上找到的数组示例的更多解释