I am writing a text spinner control for my GUI, and when creating the control, I have a function called new_selection. One of the parameters is a list of the values that can be selected. At the moment it is char *values[], but it causes a segfault when a value is accessed. The create code is:
| 1 | //gui.h: |
| 2 | typedef struct SELECTION { |
| 3 | int x; |
| 4 | int y; |
| 5 | int w; |
| 6 | int h; |
| 7 | int value; |
| 8 | char *values[]; |
| 9 | int numvalues; |
| 10 | int grey; |
| 11 | int cont; |
| 12 | BUTTON *leftarrow; |
| 13 | BUTTON *rightarrow; |
| 14 | } SELECTION; |
| 15 | |
| 16 | //gui.c: |
| 17 | SELECTION *new_selection(int x, int y, int value, char *values[], int length, int numvalues) { |
| 18 | SELECTION *tempry = (SELECTION *)malloc(sizeof(SELECTION)); |
| 19 | int n, i; |
| 20 | |
| 21 | tempry->x = x; |
| 22 | tempry->y = y; |
| 23 | tempry->leftarrow = new_button(x, y, -1, -1, "<"); |
| 24 | n = (length * text_length(font, "M")) + 4; |
| 25 | tempry->rightarrow = new_button((x + tempry->leftarrow->w + n), y, -1, -1, ">"); |
| 26 | tempry->w = (tempry->rightarrow->x + tempry->rightarrow->w) - x; |
| 27 | tempry->h = tempry->leftarrow->h; |
| 28 | tempry->value = value; |
| 29 | for(i = 0; i < numvalues; i++) { |
| 30 | tempry->values<i> = values<i>; |
| 31 | } |
| 32 | tempry->numvalues = numvalues; |
| 33 | tempry->grey = 0; |
| 34 | tempry->cont = 0; |
| 35 | |
| 36 | return tempry; |
| 37 | } |
NOTE: This is actually compiled as C++ and the file name is gui.cpp, but I do not like to use C++ and I am only using so that I will be able to use OpenLayer. Also, there is nothing wrong with my new_button() function. It works fine on it's own. The offending peice of code is:
selection->values[selection->value]
It is passed as the value parameter to textout_centre_ex. Can anybody suggest a way of fixing this?
Thanks.
EDIT:
Never mind, changing it to char **values worked. I wonder why I didn't think of that before...
I am not 100% sure but it looks like you might have a fence-post error. Doesn't your compiler give you some kind of warning about char *values[] being assumed to be of size 1?
[on a second note]
Just because you allocate space for SELECTION doesn't mean that values[] can be of any size.
No, there were no warnings at all. It doesn't matter anymore anyway.