gpt4 book ai didi

c - 带有 char* 的结构数组不会 printf() 正确吗?

转载 作者:行者123 更新时间:2023-11-30 16:49:36 26 4
gpt4 key购买 nike

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

一切似乎都存储得很好,但是当我使用“history”命令调用 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++;
}
}

最佳答案

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

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

关于c - 带有 char* 的结构数组不会 printf() 正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com