简体   繁体   English

在二维数组中存储消息的函数(在C编程中)

[英]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个功能而不是单个功能执行此操作。

  • I have 2 function. 我有2个功能。
  • function 1 -reads messages inputed by the user.(max number of 5 messages) 功能1-读取用户输入的消息。(最多5条消息)

.

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);
    }
}
  • function 2 功能2
    • it is called in function1's loop to read 5 mesaages 在function1的循环中调用它来读取5条消息
    • takes messages and passes it to its parameter 接收消息并将其传递给其参数
    • it stores message in a 2d array 它将消息存储在二维数组中
    • prints entire 2d array 打印整个二维数组

.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM