首页 > 解决方案 > Storing a string in array to use it later

问题描述

I want to store a bunch of strings, but I'm having trouble on how to store them. And after that I want to print them but later on in the program, not after I input them.

#include <stdio.h>

int main() {

    int total_people, i;
    char name[total_people][20];

    scanf("%d", &total_people);

    for(i = 0; i < total_people; i++) {

        scanf("%[^\n]", name[i][0]);

    }

    for(i = 0; i < total_people; i++) {

        printf("%s", name[i][0]);

    }


return 0;
}

I tried inputting 3 and I got a runtime error.

标签: c

解决方案


name[i][0]是数组的第一个字符name[i]。您需要一个指向第一个字符的指针,您可以使用地址运算符获得它,&&name[i][0].

或者由于数组自然衰减到指向它们的第一个元素的指针,只是name[i].


推荐阅读