docs/src/modules.md

changeset 301
0f83916c1639
parent 299
e7dfcf229625
child 302
8628147734d6
equal deleted inserted replaced
299:e7dfcf229625 301:0f83916c1639
401 *Required modules:* [Allocator](#allocator) 401 *Required modules:* [Allocator](#allocator)
402 402
403 This concrete implementation of an UCX Allocator allows you to grab some amount 403 This concrete implementation of an UCX Allocator allows you to grab some amount
404 of memory which is then handled as a stack. 404 of memory which is then handled as a stack.
405 Please note, that the term *stack* only refers to the behavior of this 405 Please note, that the term *stack* only refers to the behavior of this
406 allocator. You may still choose if you want to use stack or heap memory 406 allocator. You may still choose to use either stack or heap memory
407 for the underlying space. 407 for the underlying space.
408
409 A typical use case is an algorithm where you need to allocate and free large 408 A typical use case is an algorithm where you need to allocate and free large
410 amounts of memory very frequently. 409 amounts of memory very frequently.
410
411 The following code sample shows how to initialize a stack and push and pop
412 simple data.
413 ```C
414 const size_t len = 1024;
415 char space[len];
416 UcxStack stack;
417 ucx_stack_init(&stack, space, len);
418
419 int i = 42;
420 float f = 3.14f;
421 const char* str = "Hello!";
422 size_t strn = 7;
423
424 /* push the integer */
425 ucx_stack_push(&stack, sizeof(int), &i);
426
427 /* push the float and rember the address */
428 float* remember = ucx_stack_push(&stack, sizeof(float), &f);
429
430 /* push the string with zero terminator */
431 ucx_stack_push(&stack, strn, str);
432
433 /* if we forget, how big an element was, we can ask the stack */
434 printf("Length of string: %zu\n", ucx_stack_topsize(&stack)-1);
435
436 /* retrieve the string as sstr_t, without zero terminator! */
437 sstr_t s;
438 s.length = ucx_stack_topsize(&stack)-1;
439 s.ptr = malloc(s.length);
440 ucx_stack_popn(&stack, s.ptr, s.length);
441 printf("%" PRIsstr "\n", SFMT(s));
442
443 /* print the float directly from the stack and free it */
444 printf("Float: %f\n", *remember);
445 ucx_stack_free(&stack, remember);
446
447 /* the last element is the integer */
448 int j;
449 ucx_stack_pop(&stack, &j);
450 printf("Integer: %d\n", j);
451 ```
452
453
411 454
412 ## String 455 ## String
413 456
414 *Header file:* [string.h](api/string_8h.html) 457 *Header file:* [string.h](api/string_8h.html)
415 *Required modules:* [Allocator](#allocator) 458 *Required modules:* [Allocator](#allocator)

mercurial