Search code examples
csimgrid

SimGrid dynamic array. Cannot print element of array


I have such string:

char *string = "String";

I created a dynamic array:

xbt_dynar_t dynar = xbt_dynar_new(sizeof(char[20]), NULL);

Added this string to dynar:

xbt_dynar_push(dynar, string);

Then I want to get this string from dynamic array and print it:

char *str = xbt_dynar_get_as(dynar, 0, char*);

printf("%s\n", str);
printf("%s\n", *str); //I tried this also

Why don't I see any output?


Solution

  • You're telling the library that you want to store an object of 20 bytes, but you're passing it an object that has 7 bytes. This object being the string literal: "String".

    But then later you're trying to retrieve a pointer to that object instead of the entire object: char *str = xbt_dynar_get_as(dynar, 0, char*);

    Both don't make much sense. Either store a full object, or a pointer to that object.

    So use a struct that will hold 20 characters. Something like this:

    typedef struct 
    {
        char data[20];
    } shortstr ;
    
    shortstr s = { "String" } ;
    xbt_dynar_t dynar = xbt_dynar_new(sizeof(shortstr), NULL);
    xbt_dynar_push(dynar, &s);
    string* p = xbt_dynar_get_ptr(dynar, 0);
    printf( "%s" , p->data );
    

    Second option is to store the pointer to the string, in which case you will have to be very careful to not mix string literals and allocated strings. This is how you store string literals (and only string literals!):

    char* s = "String" ;
    xbt_dynar_t dynar = xbt_dynar_new(sizeof(char*), NULL);
    xbt_dynar_push(dynar, &s);
    char* p = xbt_dynar_get_ptr(dynar, 0);
    printf( "%s" , p );
    

    The third option is to allocate the strings (all of them have to be allocated with the same allocator), and push them to the array, in which case the deallocation will be automatic. See the example from the documentation: http://simgrid.gforge.inria.fr/simgrid/3.9/doc/group__XBT__dynar.html#XBT_dynar_exptr