使用char *而不是printf()的结构数组是正确的吗?

时间:2017-03-01 02:58:18

标签: c

我正在编写history.c和history.h,它在我正在编写的命令提示符中管理命令历史记录。

所有内容似乎都存储得很好,但是当我使用'历史记录'来调用print_history()函数时。命令它只是一遍又一遍地返回相同的字符串。

$ hello
add_history[0] command.cmd_str=hello
[0] hello
$ this
add_history[1] command.cmd_str=this
[0] this
$ is
add_history[2] command.cmd_str=is
[0] is
$ my
add_history[3] command.cmd_str=my
[0] my
$ prompt
add_history[4] command.cmd_str=prompt
[0] prompt


As you can see, above each cmd has made it to history.c with the right
string, but when this command is called it returns 'history' over and over.
$ history
    add_history[5] command.cmd_str=history
    [0] history
    [1] history
    [2] history
    [3] history
    [4] history
    [5] history

以下是history.h和history.c的代码:

#ifndef HISTORY_H
#define HISTORY_H

typedef struct cmd_struct{
    //void * pid; // not complete or correctly typed for this part of the project
    char* cmd_str; // malloc'd string containing the command that was run includ arguments
} cmd;

void init_history();
void add_history(cmd command);
void clear_history();
void print_history();

#endif
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "history.h"

int buf_index;
cmd history_buf[100];

//make sure all buffers are initialized and ready to use
void init_history(){
    buf_index = 0;
}

//adds command cmd using a cmd struct and appends to the history buffer
void add_history(cmd command){
    history_buf[buf_index] = command;
    printf("add_history[%d] command.cmd_str=%s\n", buf_index, command.cmd_str);
    buf_index++;
}

//properly frees all memory and clears the history buffer
void clear_history(){
    buf_index=0;
}

//prints the history to the command line
void print_history(){
    int i = 0;
    while(i<buf_index){
        printf("[%d] %s\n" , i ,history_buf[i].cmd_str);
        i++;
    }
}

1 个答案:

答案 0 :(得分:0)

要100%确定我们需要了解您是如何构建cmd实例的,但我可以做出有根据的猜测它正在使用公共缓冲区,因此所有cmd都有cmd_str指向同一件事(即你有多个cmd都指向同一个C字符串。)

您是否考虑过让cmd包含一个字符数组而不仅仅是一个指针?