Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct with struct pointer

Tags:

c

I am trying to define an array using pointer instead of size declaration because I do not know how many elements a map might have. Tried linked list but was not successful. I am sorry if this is a report. I am a newbie please excuse if it looks like a stupid question.

#include<stdio.h>

typedef struct _keyValue
{
    char *key;
    char *value;
} _keyValue;

typedef struct _keyValues
{
    /* _keyValue keyValue[5];  - This works*/
    _keyValue *keyValue;
    int size;
} _keyValues;

_keyValues map;

main()
{
    map.keyValue[0].key     = "Key One";
    map.keyValue[0].value   = "Value One";

    map.keyValue[1].key     = "Key Two";
    map.keyValue[1].value   = "Value Two";

    map.size = 2;

    printf("Key: %s Value: %s", map.keyValue[0].key, map.keyValue[0].value);
}
like image 653
Me Unagi Avatar asked Jul 13 '26 08:07

Me Unagi


1 Answers

map.keyValue in your example is an uninitialised pointer. You need to provide storage for the array by allocating memory using malloc

main()
{
    map.keyValue = malloc(sizeof(*map.keyValue) * 2);
    map.size = 2;

    map.keyValue[0].key     = "Key One";
    map.keyValue[0].value   = "Value One";

You can later extend the array using realloc

int newMapSize = ...
_keyValue* temp = realloc(map.keyValue, sizeof(*map.keyValue) * newMapSize);
if (temp == NULL) {
    /* allocation failed.  Handle out of memory error and exit */
}
map.keyValue = temp;
map.size = newMapSize;
// map.keyValue[0..newMapSize-1] are now available
like image 125
simonc Avatar answered Jul 14 '26 23:07

simonc