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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With