Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Need help with input_feild();

This thread is locked; no one can reply to it. rss feed Print
Need help with input_feild();
Doctor Cop
Member #16,833
April 2018
avatar

I want to create a function which accepts's key presses and displays them in a rectangular box (field).
I tried a logic which failed because a char cannot be converted to a string.

here's the logic.
char str*;
str = 'a' + event.keyboard.keycode - 1;

Here's my updated version but still not working. showing signs of memory leak, Please Help!

#SelectExpand
1int input_field(int x1, int y1, int x2, int y2, ALLEGRO_COLOR colorU, float boundry, ALLEGRO_COLOR boundry_color, ALLEGRO_FONT *font, ALLEGRO_EVENT &event, ALLEGRO_EVENT_QUEUE *ev_queue) 2{ 3 int x=0; 4 al_draw_filled_rounded_rectangle(x1, y1, x2, y2, 10, 10, colorU); 5 al_draw_rounded_rectangle(x1, y1, x2, y2, 10, 10, boundry_color, boundry); 6 7 if(event.mouse.x >= x1 && event.mouse.x <= x2 && event.mouse.y >= y1 && event.mouse.y <= y2 && event.mouse.button & 1 && event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) 8 { 9 char* str1; 10 //int p=0; 11 while(1) 12 { 13 al_draw_text(font, al_map_rgb(0, 153, 0), x1+5+x, y1+5, 1, "|"); 14 al_wait_for_event(ev_queue, &event); 15 switch(event.keyboard.keycode) 16 { 17 case 1: 18 strcat(str1, "a"); 19 break; 20 case 2: 21 strcat(str1, "b"); 22 break; 23 case 3: 24 strcat(str1, "c"); 25 break; 26 case 4: 27 strcat(str1, "d"); 28 break; 29 case 5: 30 strcat(str1, "e"); 31 break; 32 case 6: 33 strcat(str1, "f"); 34 break; 35 case 7: 36 strcat(str1, "g"); 37 break; 38 case 8: 39 strcat(str1, "h"); 40 break; 41 case 9: 42 strcat(str1, "i"); 43 break; 44 case 10: 45 strcat(str1, "j"); 46 break; 47 case 11: 48 strcat(str1, "k"); 49 break; 50 case 12: 51 strcat(str1, "l"); 52 break; 53 case 13: 54 strcat(str1, "m"); 55 break; 56 case 14: 57 strcat(str1, "n"); 58 break; 59 case 15: 60 strcat(str1, "o"); 61 break; 62 case 16: 63 strcat(str1, "p"); 64 break; 65 case 17: 66 strcat(str1, "q"); 67 break; 68 case 18: 69 strcat(str1, "r"); 70 break; 71 case 19: 72 strcat(str1, "s"); 73 break; 74 case 20: 75 strcat(str1, "t"); 76 break; 77 case 21: 78 strcat(str1, "u"); 79 break; 80 case 22: 81 strcat(str1, "v"); 82 break; 83 case 23: 84 strcat(str1, "w"); 85 break; 86 case 24: 87 strcat(str1, "x"); 88 break; 89 case 25: 90 strcat(str1, "y"); 91 break; 92 case 26: 93 strcat(str1, "z"); 94 break; 95 } 96 al_draw_text(font, al_map_rgb(0, 153, 0), x1+10, y1+5, 1, str1); 97 x+5; 98 //printf("%s", str1); 99 if(event.keyboard.keycode == ALLEGRO_KEY_ENTER) 100 { 101 break; 102 } 103 al_flip_display(); 104 105 } 106 } 107 return 0; 108}

Michael Weiss
Member #223
April 2000

Instead of using keyboard.keycode try using keyboard.unichar

see: http://liballeg.org/a5docs/trunk/events.html

look under the ALLEGRO_EVENT_KEY_CHAR section

then you wont need 26 case blocks...

Doctor Cop
Member #16,833
April 2018
avatar

I want help with converting char to string also or a way to draw the unichar in al_draw_text(); function, if you can help please reply.

Mark Oates
Member #1,146
March 2001
avatar

converting char to string

I would typically do that:

#include <sstream>
#include <string>


char c = 'p';
std::string result;

std::stringstream ss;
ss << c;
result = ss.str();

Michael Weiss
Member #223
April 2000

To convert a char to a string you could do this:

int chr = 65; // "A"
char str[256];
str[0] = chr;
str[1] = NULL;

or

int chr = 65; // "A"
char str[256];
sprintf(str, "%c", chr);

There are probably better ways to do this though, I'm looking forward to being corrected!

Doctor Cop
Member #16,833
April 2018
avatar

*Mark Oates*.

I am using C so I can't use C++ strings!
and
thanks for help *Michel Weiss* but I actually thought of it earlier, it didn't work.
I can't convert str[256] to a char* and that's the real problem.
How to print different chars with exact distance replacement as in a string.

If there's a way to create an input field like some library for allegro5 or code for that, please share.

Michael Weiss
Member #223
April 2000

I implemented my own editable text field like this.
Its not pretty, but it works for me.
I needed a way to let the user edit the server name or IP address for netgame.

Sorry its not a simple example with only the editable text field part.

I had to include my function that shows the cursor position and my proc_controller
function that processes the event queue...etc

Its quite a lot of stuff, but maybe there's something in there you can use...

#SelectExpand
1 2char fst[80]; 3extern char m_serveraddress[256]; 4 5void edit_server_name(void) 6{ 7 strcpy(fst, m_serveraddress); 8 int char_count = strlen(fst); 9 int cursor_pos=0; 10 int old_cp=0; 11 int blink_count = 3; 12 int blink_counter = 0; 13 while (key[ALLEGRO_KEY_ENTER]) proc_controllers(); 14 int quit = 0; 15 while (!quit) 16 { 17 int tx = SCREEN_W/2; 18 int ty = SCREEN_H/2; 19 int tw = (char_count+1)*4; 20 21 al_flip_display(); 22 // clear text background 23 al_draw_filled_rectangle(tx-tw-8, ty-4-2, tx+tw+18, ty+4+3, palette_color[0]); 24 25 al_draw_text(font, palette_color[15], tx, ty-14, ALLEGRO_ALIGN_CENTER, "Set Server IP or Hostname"); 26 // frame text 27 al_draw_rectangle (tx-tw-1, ty-4-1, tx+tw+6, ty+6, palette_color[15], 1); 28 29 rtextout_centre(NULL, fst, tx, ty+1, 15, 1, 0, 1); 30 31 if (blink_counter++ < blink_count) show_cursor(fst, cursor_pos, tx, ty-3, 15, 0, 0); 32 else show_cursor(fst, cursor_pos, tx, ty-3, 15, 1, 0); 33 if (blink_counter> blink_count*2) blink_counter = 0; 34 35 if (cursor_pos != old_cp) 36 { 37 show_cursor(fst, old_cp, tx, ty-3, 15, 1, 0); // erase old blinking cursor if moved 38 old_cp = cursor_pos; 39 blink_counter = 0; 40 } 41 42 al_rest(.08); 43 int k = proc_controllers(); 44 if (key[ALLEGRO_KEY_RIGHT]) 45 { 46 if (++cursor_pos > char_count) cursor_pos = char_count; 47 } 48 if (key[ALLEGRO_KEY_LEFT]) 49 { 50 if (--cursor_pos < 0) cursor_pos = 0; 51 } 52 if ((key[ALLEGRO_KEY_DELETE]) && (cursor_pos < char_count)) 53 { 54 for (int a = cursor_pos; a < char_count; a++) 55 fst[a]=fst[a+1]; 56 --char_count; 57 fst[char_count] = (char)NULL; // set last to NULL 58 } 59 if ((key[ALLEGRO_KEY_BACKSPACE]) && (cursor_pos > 0)) 60 { 61 cursor_pos--; 62 for (int a = cursor_pos; a < char_count; a++) 63 fst[a]=fst[a+1]; 64 char_count--; 65 fst[char_count] = (char)NULL; // set last to NULL 66 } 67 68 k = Key_pressed_ASCII; 69 if ((k>31) && (k<127)) // insert if alphanumeric or return 70 { 71 // move over to make room 72 for (int a = char_count; a>=cursor_pos; a--) 73 fst[a+1]=fst[a]; 74 75 // set char 76 fst[cursor_pos] = k; 77 78 // inc both 79 cursor_pos++; 80 char_count++; 81 82 fst[char_count] = (char)NULL; // set last to NULL 83 } 84 if (key[ALLEGRO_KEY_ENTER]) 85 { 86 while (key[ALLEGRO_KEY_ENTER]) proc_controllers(); 87 strcpy(m_serveraddress, fst); 88 quit = 1; 89 } 90 91 if (key[ALLEGRO_KEY_ESCAPE]) 92 { 93 while (key[ALLEGRO_KEY_ESCAPE]) proc_controllers(); 94 quit = 1; 95 } 96 } 97} 98 99 100void show_cursor(char *f, int cursor_pos, int xpos_c, int ypos, int cursor_color, int restore, int rot) 101{ 102 int len = strlen(f); 103 char dt[40][120]; 104 int row=0, col=0, cursor_row=0, cursor_col=0; 105 // get cursor row and column and fill dt 106 for (int a=0; a<len+1; a++) 107 { 108 if (a == cursor_pos) 109 { 110 cursor_row = row; 111 cursor_col = col; 112 } 113 if (f[a] == 13) // line break 114 { 115 row++; 116 col=0; 117 dt[row][col] = (char)NULL; // in case len = 0 118 } 119 else // regular char 120 { 121 dt[row][col] = f[a]; 122 col++; 123 dt[row][col] = (char)NULL; 124 } 125 } 126 127 // make a string from the cursor text char 128 msg[0] = f[cursor_pos]; 129 msg[1] = 0; 130 131 int x, y; 132 x = cursor_col*8+xpos_c - strlen(dt[cursor_row])*4; 133 y = ypos+cursor_row*8; 134 135 if (restore) // black background, text color text 136 { 137 al_draw_filled_rectangle(x, y, x+8, y+8, palette_color[0]); 138 al_draw_text(font, palette_color[cursor_color], x, y, 0, msg); 139 } 140 141 else // red background, black text 142 { 143 al_draw_filled_rectangle(x, y, x+8, y+8, palette_color[10]); 144 al_draw_text(font, palette_color[0], x, y, 0, msg); 145 } 146} 147 148 149 150int proc_events(ALLEGRO_EVENT ev, int ret) 151{ 152 if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) fast_exit(0); 153 if (ev.type == ALLEGRO_EVENT_MOUSE_WARPED) 154 { 155 mouse_x = ev.mouse.x / les; 156 mouse_y = ev.mouse.y / les; 157 } 158 if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) 159 { 160 mouse_x = ev.mouse.x / les; 161 mouse_y = ev.mouse.y / les; 162 mouse_z = ev.mouse.z / les; 163 mouse_dx = ev.mouse.dx; 164 mouse_dy = ev.mouse.dy; 165 mouse_dz = ev.mouse.dz; 166 } 167 if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) 168 { 169 if (ev.mouse.button == 1) mouse_b1 = 1; 170 if (ev.mouse.button == 2) mouse_b2 = 1; 171 if (ev.mouse.button == 3) mouse_b3 = 1; 172 if (ev.mouse.button == 4) mouse_b4 = 1; 173 } 174 if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) 175 { 176 if (ev.mouse.button == 1) mouse_b1 = 0; 177 if (ev.mouse.button == 2) mouse_b2 = 0; 178 if (ev.mouse.button == 3) mouse_b3 = 0; 179 if (ev.mouse.button == 4) mouse_b4 = 0; 180 } 181 if (ev.type == ALLEGRO_EVENT_KEY_DOWN) 182 { 183 int k = ev.keyboard.keycode; 184 key[k] = true; 185 ret = k; 186 } 187 if (ev.type == ALLEGRO_EVENT_KEY_UP) 188 { 189 int k = ev.keyboard.keycode; 190 key[k] = false; 191 if (k == ALLEGRO_KEY_PRINTSCREEN) key[k] = true; // special exception to make PRINTSCREEN work 192 } 193 if (ev.type == ALLEGRO_EVENT_KEY_CHAR) 194 { 195 Key_pressed_ASCII = ev.keyboard.unichar; 196 } 197 if (ev.type == ALLEGRO_EVENT_JOYSTICK_AXIS) 198 { 199 int jy = getJoystickNum(ev.joystick.id); 200 int jo = 0; // offset 201 if (jy == 0) jo = 0; 202 if (jy == 1) jo = 20; 203 int ax = ev.joystick.axis; 204 float pos = ev.joystick.pos; 205 if (ax == 0) // x axis 206 { 207 key[130+jo] = false; 208 key[131+jo] = false; 209 if (pos > 0) key[131+jo] = true; 210 if (pos < 0) key[130+jo] = true; 211 } 212 if (ax == 1) // y axis 213 { 214 key[128+jo] = false; 215 key[129+jo] = false; 216 if (pos > 0) key[129+jo] = true; 217 if (pos < 0) key[128+jo] = true; 218 } 219 } 220 if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN) 221 { 222 int jy = getJoystickNum(ev.joystick.id); 223 int sc = get_scan_code_from_joystick(jy, 1, ev.joystick.button); 224 key[sc] = true; 225 } 226 if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_UP) 227 { 228 int jy = getJoystickNum(ev.joystick.id); 229 int sc = get_scan_code_from_joystick(jy, 1, ev.joystick.button); 230 key[sc] = false; 231 } 232 return ret; 233} 234 235 236 237 238 239 240int proc_controllers() 241{ 242 int ret = 0; 243 int done = 0; 244 int menu_timer_wait = 1; 245 246 if (key[ALLEGRO_KEY_PRINTSCREEN]) key[ALLEGRO_KEY_PRINTSCREEN] = 0; // special exception to make PRINTSCREEN work 247 Key_pressed_ASCII = 0; 248 if (!fullscreen) // detect if window was moved 249 { 250 al_get_window_position(display, &l_spx, &l_spy); 251 if ((l_spx != disp_x_curr) || (l_spy != disp_y_curr)) 252 proc_screen_change(disp_w_curr, disp_h_curr, l_spx, l_spy, fullscreen); 253 } 254 while (!done) 255 { 256 done = 1; // default 257 while (!al_is_event_queue_empty(event_queue)) 258 { 259 ALLEGRO_EVENT ev; 260 if (ev.type == ALLEGRO_EVENT_TIMER) menu_timer_wait = 0; 261 262 if (al_get_next_event(event_queue, &ev)) 263 { 264 if (ev.type == ALLEGRO_EVENT_DISPLAY_RESIZE) 265 { 266 // check to see if we have more resize events piling up 267 ALLEGRO_EVENT ev2; 268 269 while (al_get_next_event(event_queue, &ev2)) 270 { 271 if (ev2.type == ALLEGRO_EVENT_DISPLAY_RESIZE) ev = ev2; 272 else ret = proc_events(ev2, ret); 273 } 274 proc_screen_change(ev.display.width, ev.display.height, disp_x_curr, disp_y_curr, fullscreen); 275 } 276 else ret = proc_events(ev, ret); 277 } 278 } 279 280 if (game_exit) // if called from menu only do key check for active local player 281 { 282 clear_keys(active_local_player); 283 player_key_check(active_local_player); 284 function_key_check(); 285 if (menu_timer_wait) done = 0; 286 } 287 else // this is run if a game is in progress 288 { 289 function_key_check(); 290 extern int level_done; 291 292 for (int p=0; p<NUM_PLAYERS; p++) 293 if (players[p].active) // cycle all active players 294 { 295 if (players[p].control_method == 0) // local single player control 296 { 297 if (level_done) add_game_move(passcount, 6, 0, 0); // insert level done into game move 298 clear_keys(p); 299 player_key_check(p); 300 set_comp_move_from_controls(p); 301 if (players1[p].comp_move != players1[p].old_comp_move) 302 { 303 players1[p].old_comp_move = players1[p].comp_move; 304 add_game_move(passcount, 5, p, players1[p].comp_move); 305 } 306 } 307 if (players[p].control_method == 1) rungame_key_check(p, ret); // run game from file 308 #ifdef NETPLAY 309 if (players[p].control_method == 3) server_local_control(p); 310 if (players[p].control_method == 4) client_local_control(p); 311 #endif 312 set_controls_from_game_move(p); // common for all players 313 } // end of active player iterate 314 proc_game_move(); // run once per frame to process system messages from game_move 315 } // end of if (!game_exit) 316 } 317 //printf("ret:%d\n", ret); 318 return ret; 319}

Mark Oates
Member #1,146
March 2001
avatar

I am using C so I can't use C++ strings!

Ah, okie dokie. 👍

Michael Weiss
Member #223
April 2000

You said: I can't convert str[256] to a char* and that's the real problem.

Why can't you convert str[256] to a char* ?

Are you trying to get a string to pass to 'al_draw_text()' ?

Can you post some code that shows what you are trying to convert to what?
Or more specifically what you tried that didn't work?

Are you trying to build a string from char's returned from events?
That should be very simple to do.

#SelectExpand
1 2// setup 3char str[256]; 4str[0] = NULL; 5pos = 0; 6 7// get a char from events and add it to the string 8str[pos] = event.keyboard.unichar; 9pos++; 10str[pos] = NULL; // make sure to terminate the string with NULL 11 12// display the string 13al_draw_text(font, color, x, y, 0, str);

this will work, I've done it many times.

char str[256] is an array of char
str is a pointer to the first element (just like any array)

Maybe I'm missing something and you're trying to do something else, let us know.

Edgar Reynaldo
Member #8,592
May 2007
avatar

I want to create a function which accepts's key presses and displays them in a rectangular box (field).
I tried a logic which failed because a char cannot be converted to a string.

here's the logic.
char str*;
str = 'a' + event.keyboard.keycode - 1;

Here's my updated version but still not working. showing signs of memory leak, Please Help!

...

 char* str1;

You're missing some fundamentals of C programming. First of all, 'str1' in your code there is just a pointer. It is NOT a string. It's a pointer of type char. That means it points to a char value. You have to allocate memory for the string somewhere. Second of all you didn't initialize the value of 'str1'. Which means it could hold ANY value.

I can't convert str[256] to a char* and that's the real problem.

Uh, why not? Did your compiler output an error? It shouldn't.

#SelectExpand
1const int BUFSIZE = 1024; 2char buf[BUFSIZE] = {0}; 3 4/// Option one, direct memory access 5buf[0] = 'a'; 6 7/// Option two, string concatenation 8strcat(buf , "a"); 9 10/// Option three, format string 11sprintf(buf , "%c" , 'a'); 12 13char* alias = &buf[0];/// Take the address of the first element of the char array 14char* alias2 = buf;/// direct assignment works

Quote:

If there's a way to create an input field like some library for allegro5 or code for that, please share.

Here's an example of how to use an ALLEGRO_EVENT_KEY_CHAR event to create an input field :

https://github.com/EdgarReynaldo/EagleGUI/blob/master/TINS2017/src/Game.cpp#L380-L443

Doctor Cop
Member #16,833
April 2018
avatar

Edgar Reynaldo:-
Thank you for your advice and I was told that char* is a new way to initialize a string so that's why it happened.

You said and I quote "Uh, why not? Did your compiler output an error? It shouldn't.",
Yes my compiler throws an error:- C++11 doesn't support conversion from char to a string.

Thanx for your link:- https://github.com/EdgarReynaldo/EagleGUI/blob/master/TINS2017/src/Game.cpp#L380-L443, I will make utilization of your code in future but for now, I want to know what I am doing wrong.

Michael Weiss:-
Thank you for your suggestion but I already tried it and it successfully compiled but it produces a runtime error.
I am posting my compleat code so please read it, it's in attachments.
It just stops working when I click in my input_field() box.

For now, I replaced my code with your code.

Edgar Reynaldo
Member #8,592
May 2007
avatar

Thank you for your advice and I was told that char* is a new way to initialize a string so that's why it happened.

You have to understand what is happening when you declare a char* like that.

This code :

char* str = "some_text_goes_here";

actually translates to :

static char str_array[20] = {'s','o','m','e','_','t','e','x','t','_',
                   'g','o','e','s','_','h','e','r','e','\0'};
char* str = &str_array[0];

The compiler declares a static string and gives you a pointer to it.

Quote:

Yes my compiler throws an error:- C++11 doesn't support conversion from char to a string.

You said you're using C, not C++11. Make up your mind. It makes a difference.

Quote:

Thank you for your suggestion but I already tried it and it successfully compiled but it produces a runtime error.
I am posting my compleat code so please read it, it's in attachments.
It just stops working when I click in my input_field() box.

You're not using events properly at all. You HAVE to check the event type before you access the event union or else you will get complete garbage.

Try reading the manual. http://liballeg.org/a5docs/trunk/events.html

Doctor Cop
Member #16,833
April 2018
avatar

I want to make a GUI input field function which I can use for c and c++ both.

If I use any GUI API for my game instead of trying to create my own, will it be the optimal solution, I mean will my game become large by adding additional library just for GUI purpose.

Edgar Reynaldo
Member #8,592
May 2007
avatar

In C++, you can't assign the value of a const char* (a string in C++) to a char*. It's illegal because the memory isn't yours. You have to declare your own buffer.

char* str = "abc";/// Illegal in C++, deprecated in C
                  /// "abc" is a static const char array
                  /// and it is illegal to remove the const without a cast

You don't need a GUI library for a single widget.

Check the event type first, and then access the union.

#SelectExpand
1if (ev.type == EAGLE_EVENT_KEY_CHAR) { 2 int kc = ev.keyboard.keycode; 3 int ascii = ev.keyboard.unichar; 4 if (isalpha(ascii) || isnum(ascii) || isspace(ascii)) { 5 buf[index++] = (char)ascii; 6 } 7 else { 8 9 switch (kc) { 10 case ALLEGRO_KEY_LEFT : 11 --index; 12 if (index < 0) {index = 0;} 13 break; 14 case ALLEGRO_KEY_RIGHT : 15 ++index; 16 if (index >= BUFSIZE) {index = BUFSIZE - 1;} 17 case ALLEGRO_KEY_ENTER : finish(); break; 18 case ALLEGRO_KEY_BACKSPACE : erase_current(); break; 19 case ETC : break; 20 default : break; 21 }; 22}

This should give you an idea of how to monitor keyboard events.

Doctor Cop
Member #16,833
April 2018
avatar

Thanks for your help and now I am going to use your library for GUI - (EAGLE5).
again thanks for your advice.

What is SantaHack2016?
is it a game?

again thanks and especially because of EAGLE5.cbp. I love code blocks builds.

Edgar Reynaldo
Member #8,592
May 2007
avatar

bamccaig
Member #7,536
July 2006
avatar

Something that was hinted at, but not fully explained, is the difference between `char []` and `char *` and what they're used for.

An array, which is indicated by the square brackets `[]` allocates a sequence of bytes on the program's call stack. This is just like other local variables that you define, like int and char. It exists until the function returns, and is automatically released.

A char pointer can either point to a single character, or to an array of characters, or NULL which signifies that memory has not been allocated yet, or garbage if you forget to initialize it (never do this because it's an obscure crash waiting to happen). The character or characters that you point to can either be on the stack or on the heap.

The heap is like a pool of memory that you can allocate that survives even when a function returns. It is accessible from anywhere in the program as long as you know its address in memory. In C, you use the malloc family of functions to allocate memory on the heap, and in C++ you use the new and new[] operators. Anything that you allocate in this way must be cleaned up after using free() for malloc() style allocations and the delete or delete[] operators for new allocations. A memory leak is said to have occurred when you forget to do this.

#SelectExpand
1#include <assert.h> 2#include <stdio.h> 3#include <stdlib.h> 4#include <string.h> 5 6int main(int argc, char * argv[]) 7{ 8 char c = 'A'; 9 const char * const cs = "static string of characters"; 10 char s[255] = "string of characters"; 11 12 char * pc = &c; // pc points to c, which contains 'A'. 13 char * ps = s; // ps points to s, which contains "string of characters" (which is nul-byte terminated). 14 15 // dc is a single character (not a string!) allocated on the heap. 16 // It is initially pointing to garbage, but then I assign 'B' to its memory slot. 17 char * dc = malloc(sizeof(char) * 1); 18 assert(dc); 19 *dc = 'B'; 20 21 // ds is a character array allocated on the heap with a maximum length of 512 22 // characters. If this is used as a C string then it can only store 511 characters 23 // plus the nul-terminating character. The actual string is garbage right now. 24 // We have allocated the memory, but not initialized it yet. 25 char * ds = malloc(sizeof(char) * 512); 26 assert(ds); 27 28 // This is one way to initialize it. You can also use `calloc` instead which does 29 // this for you. This makes it an empty string "" (in a 512 character array). 30 memset(ds, 0, 512); 31 32 snprintf(ds, 512, 33 "c='%c' cs='%c' s=\"%s\", pc='%c', ps=\"%s\", dc='%c', ds=\"%s\"", 34 c, *cs, s, *pc, ps, *dc, ds); 35 36 puts(ds); 37 38 // Must release the memory when we're done with it. 39 free(dc); 40 free(ds); 41 42 return 0; 43}

In the snippet above I've tried to demonstrate the basic ways that character arrays and pointers are used. The thing that you were forgetting to do was allocate memory for the string. Whether you should do this on the stack or heap depends on how big it will be and whether you need it only temporarily or you need to be able to return it from a function. This is all about memory management. C and to an extent C++ put this burden on you do manage it. It's fun to do, but it's also hard to do perfectly. You definitely should try to understand these concepts now because it'll take a while to really get full control of this.

Doctor Cop
Member #16,833
April 2018
avatar

bamccaig: Thanks for this information, I can't express how glad I am!
Is there any site where I can find more programming knowledge like this?

Edgar Reynaldo: Thanks man, I really appreciate that but I already ripped off the logic from SDL's "TextInput" function.
Thanks for your help!

Go to: