c - 在我的结构中访问我的图形时,它会打印一个空行
问题描述
这是我正在使用的结构。
#define MAX_CAR_LEN 12 ///< length does not include the trailing NUL byte
/// Racer_S structure represents a racer's row, position and display graphic.
typedef struct Racer_S {
int row; ///< vertical row or "racing lane" of a racer
int distance; ///< column of rear of car, marking its position in race
char *graphic; ///< graphic is the drawable text of the racer figure
} Racer;
当我调用此函数时,它内部一切正常并正确创建所有内容。我能够很好地访问行和距离。当我尝试打印图形时,我在终端中打印了一个空行。我相信这可能是因为结构中的“图形”是一个 char*,但我为它分配了一个固定大小的 char 数组。当这个函数被调用并传入名称“Tom”时,图形应该是“~O=Tom----o>”。我是C新手,我做错了什么?
Racer * make_racer( char *name, int row ){
//Creating a newRacer instance
Racer *newRacer = malloc(sizeof(*newRacer));
newRacer->graphic = (char*)malloc(MAX_CAR_LEN);
char car[MAX_CAR_LEN] = "~O="; //"~O=-------o>"
char *pCar;
int length = strlen(name) + 2;
//Add the name after the engine of the car
for (int i = 0; i < length; ++i)
car[i+3] = name[i];
//Calculate the amount of dashes needed
int printDashes = 7 - strlen(name);
//add the extra dashes
for (int j = 1; j <= printDashes; ++j)
car[length + j] = '-';
// creates the end of the car
car[MAX_CAR_LEN-2] = 'o';
car[MAX_CAR_LEN-1] = '>';
pCar = strdup(car);
newRacer->row = row;
newRacer->distance = 0;
newRacer->graphic = &car[0];
// printf("%s\n", car);
return newRacer;
}
这是我在 main 中运行以测试它的代码
Racer *t = make_racer("Tom", 4);
printf("%s\n", t->graphic);
解决方案
您在问题中提到了以下陈述。
这是我在 main 中运行以测试它的代码
acer *t = make_racer("Tom", 4); printf("%s\n", t->graphic);
在make_racer函数中,您使用了一个名为car的本地字符数组变量并将地址分配给newRacer->graphic。这个变量(char car[MAX_CAR_LEN+1] ;) 从函数返回后内存超出范围。
请参阅此线程以了解有关 C 中本地范围的更多信息。
现在要解决您的问题,在make_racer函数中,您还必须为 newRacer->graphic动态分配内存。
Racer * make_racer( char *name, int row ){
:
Racer *newRacer = malloc(sizeof(*newRacer));
newRacer->graphic = (char*)malloc(MAX_CAR_LEN+1);
:
//newRacer->graphic = &car[0]; # this is wrong.
strcpy(newRacer->graphic,car); //copy the content to allocated memory.
/*
* Warning:Just i am pointing out the issue here.
* strcpy may cause buffer over run.
* You have to use snprintf/strncpy family to prevent buffer overrun.
*/
}
确保释放 main 中的内存。
int main() {
:
free(newRacer->graphic); //before free the momory for "newRacer"
free(newRacer);
}
推荐阅读
- c++ - 无法播放声音文件 gstreamer C++
- java - Vaadin 8 到 14 迁移:在 eclipse 中运行时找不到 .cache.js 文件
- qt - 使用 createObject (null) 创建一个新的顶级 QML 窗口
- bootstrap-4 - 引导显示密码不显示眼睛图标或工作
- powershell - 将 sed 命令从 cUrl 转换为 Powershell
- databricks - 如何在 databricks 集群上运行多个 Spark 流应用程序
- python - 如果重复则合并 2D 列表
- python - 如何使用向量表示通过聚类关键字对描述中的单词进行分组
- angular - 单击日期选择器时,单元格编辑器上的 Ag-grid Angular Material Datepicker 失去焦点
- django - Django URL 不呈现模板