[英]function storing messages in a 2d array (in C programming)
What I want to achieve is a C program that stores names every time the user enters a name like the following: 我要实现的是一个C程序,该程序在用户每次输入名称时都存储名称,如下所示:
func1: read: john func1:阅读:约翰
func2 print john func2打印约翰
func1: read: michael func1:阅读:迈克尔
func2 print: john print: michael func2打印:约翰打印:迈克尔
I want to know how to do this in 2 functions and not a single function. 我想知道如何使用2个功能而不是单个功能执行此操作。
. 。
void read(void)
{
int i;
char read[100];
// char * msg = (char *) malloc(sizeof(msg));
//i want to read 5 messages from user
for (i=0;i<5;i++)
{
scanf("%s",&read);
//i want to copy the message read into a variable msg,
//i dont know why i am doing this
//strcpy(msg,read);
//i want to call the store funcion
store(read);
}
}
. 。
int store(char *stock)
{
printf("saving.....stored\n");
char share[5][10]; //this is my 2d array to hold 5
//messages/names of 10 chars long
int i=0;
char * savedmsg = (char *) malloc(sizeof(savedmsg));
strcpy(share[i],stock);
printf("%s\n",share[i]);
i++;
printf("%s\n", share[1]);
}
I have started learning C this week but I presume the error I am getting is that func2 keeps re-initializing i=0;
我本周开始学习C,但是我想得到的错误是func2不断重新初始化i=0;
where I want it to increment i++;
我希望它增加i++;
so func2 keeps overwriting the first index in 2d array. 因此func2会继续覆盖2d数组中的第一个索引。
Thanks for future help. 感谢您将来的帮助。
Instead of using 而不是使用
int i=0;
declare it as static
like this: 像这样声明它为static
:
static int i=0;
The value of i
is saved during function call. i
的值在函数调用期间保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.