当访问我的结构中的图形时,它会打印一个空行

时间:2018-11-14 02:44:38

标签: c string pointers char c99

这是我正在使用的结构。

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

这是我正在主程序中运行以对其进行测试的代码

Racer *t = make_racer("Tom", 4);
printf("%s\n", t->graphic);

1 个答案:

答案 0 :(得分:0)

您在问题中提到了以下声明。

  

这是我正在主程序中运行以对其进行测试的代码

acer *t = make_racer("Tom", 4);
printf("%s\n", t->graphic);

make_racer 函数中,您使用了一个名为 car 的本地字符数组变量,并将地址分配给了 newRacer-> graphic 。从函数返回后,此变量(char car [MAX_CAR_LEN + 1];)内存超出范围。

请参考this thread以了解有关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.
     */
}

确保释放主内存。

int main() {
:
    free(newRacer->graphic);    //before free the momory for "newRacer"
    free(newRacer);
}