realloc - converting int to char
Posted
by Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2010-05-29T23:25:20Z
Indexed on
2010/05/29
23:32 UTC
Read the original article
Hit count: 328
I'm converting an array of integers into a char by iterating through the whole array, and then I'm adding the resulting string to ncurses's method new_item
. For some reason I'm doing something wrong the way I reallocate
memory, thus I get the the first column as:
-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 *));
// right here
char *convert = NULL;
for(i = 0; i < n_choices; ++i){
convert = (char *) realloc (convert, 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;
}
}
free(convert);
unpost_menu(my_menu);
free_item(my_items[0]);
free_item(my_items[1]);
free_item(my_items[2]);
free_item(my_items[3]);
free_item(my_items[4]);
free_menu(my_menu);
endwin();
}
© Stack Overflow or respective owner