realloc - 将int转换为char

时间:2010-05-29 23:25:20

标签: c string ncurses realloc

我通过遍历整个数组将整数数组转换为char,然后我将结果字符串添加到ncurses的方法new_item中。出于某种原因,我做错了我reallocate内存的方式,因此我得到了第一列:

-4 Choice 1                 0 Choice 1
 4 Choice 2                 1 Choice 1
 4 Choice 3  - Instead of - 2 Choice 1
 4 Choice 4                 3 Choice 1
 4 Exit                     4 Choice 1

-

#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <menu.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#define CTRLD     4

char *choices[] = {
                        "Choice 1",
                        "Choice 2",
                        "Choice 3",
                        "Choice 4",
                        "Exit",
                  };
int table[5]={0,1,2,3,4}; 
int main()
{    ITEM **my_items;
    int c;              
    MENU *my_menu;
    int n_choices, i;
    ITEM *cur_item;

    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    n_choices = ARRAY_SIZE(choices);
    my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));

    char *convert = NULL;
    for(i = 0; i < n_choices; ++i){
        convert = (char *) malloc ( sizeof(char) * 4);
        sprintf(convert, "%i", table[i]); 
        my_items[i] = new_item(convert, choices[i]);
    }
    my_items[n_choices] = (ITEM *)NULL;

    my_menu = new_menu((ITEM **)my_items);
    mvprintw(LINES - 2, 0, "F1 to Exit");
    post_menu(my_menu);
    refresh();

    while((c = getch()) != KEY_F(1))
    {   switch(c)
        {   case KEY_DOWN:
                menu_driver(my_menu, REQ_DOWN_ITEM);
                break;
            case KEY_UP:
                menu_driver(my_menu, REQ_UP_ITEM);
                break;
        }
    }

    char *n = NULL, *d = NULL;

    unpost_menu(my_menu);
    free_menu(my_menu);
    for(i = 0; i < n_choices; ++i){
       n = (char *) item_name (my_items[i]);
       free (n);
       d = (char *) item_description (my_items[i]);
       free (d);
       free_item(my_items[i]);
    }

    free(my_items);
    endwin();
}

**更新:此问题已修复。见上面的代码!

1 个答案:

答案 0 :(得分:1)

您再次尝试realloc相同大小的相同内存块,realloc只返回相同的内存块。因此,您将覆盖convert的早期值,并在所有项目中存储相同的char数组。

您应该使用malloc代替:

// right here
char *convert = NULL;
for(i = 0; i < n_choices; ++i){
    convert = (char *) malloc (sizeof(char) * 4);
    sprintf(convert, "%i", table[i]); 
    my_items[i] = new_item(convert, choices[i]);
}