c - 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.
解决方案
name[i][0]
是数组的第一个字符name[i]
。您需要一个指向第一个字符的指针,您可以使用地址运算符获得它,&
如&name[i][0]
.
或者由于数组自然衰减到指向它们的第一个元素的指针,只是name[i]
.
推荐阅读
- c - 静态分配的数组如何在 C 中的内存中布局?
- javascript - 试图让导航在本机反应的页面之间工作
- python - 打印文本文件的行号
- python - 填充和重塑熊猫数据框
- javascript - 前端开发人员面试编码问题:a 未定义,b 已定义?
- xml - Outlook Manifest 在 Web Outlook 中有效,无法在桌面 Outlook 中正确安装
- javascript - 通过使用 jQuery 删除类来关闭下拉菜单
- kotlin - 如何通过 Kotlin 在 Redshift JDBC PreparedStatement 中使用和设置数组
- sql-server - xml根在sql中重复多次?
- amazon-web-services - 审计 AWS 上的 k8s 集群事件