首页 > 解决方案 > 在我的结构中访问我的图形时,它会打印一个空行

问题描述

这是我正在使用的结构。

#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);

标签: cstringpointerscharc99

解决方案


您在问题中提到了以下陈述。

这是我在 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);
}

推荐阅读