so I'm trying to allocate memory for an array of strings thats in a struct: This is the struct:
typedef struct{
int aisleNumber;
char **aisleProducts;
}Aisle;
And this is how I allocate the memory:
Aisle.aisleProducts = (aisleProducts*)malloc( sizeof(aisleProducts) );
For now, I only need space for one string in the array, hence why I'm not multiplying the size. Still doesn't work and I don't know why...
Any help would be appreciated.
CodePudding user response:
The malloc
call is senseless. For an array of pointers you should allocate n * sizeof(char*)
and since malloc
returns a pointer to the first allocated element (which is a pointer), you should not cast the result to char*
but treat it as a char**
.
Example:
#include <stdlib.h>
aisles.aisleProducts = malloc( n * sizeof(*Aisle.aisleProducts) );
Or equivalent:
#include <stdlib.h>
aisles.aisleProducts = malloc( n * sizeof(char*) );
Or equivalent:
#include <stdlib.h>
aisles.aisleProducts = malloc( sizeof(char* [n]) );
CodePudding user response:
It's not working because sizeof(...) returns a compile-time constant value. Your struct is exactly 12 bytes (at least when targetting a 64-bit platform). The int value is 4 bytes, while the pointer (like all other pointers) is 8 bytes. If you want to allocate more memory for your strings, then you'll have to allocate and assign your pointers manually, maybe in a loop. Let's say you have 4 strings:
// Allocate space for the starting pointers
Aisle.aisleProducts = (char**) malloc(sizeof(char*) * 4);
// Then more space for each individual string (for convenience, let's give each one of them 64 bytes)
for (int i = 0; i < 4; i )
{
Aisle.aisleProducts[i] = (char*) malloc(sizeof(char) * 64);
}
// Assign your strings...
Edit: as other people have noted, 12 bytes is the theoretical size of the struct, but in practice, it will be aligned to an arbitrary value.
CodePudding user response:
You can try
Aisle* pAisle = (Aisle*)malloc(sizeof(Aisle));
pAisle->aisleProducts = (char**)malloc(sizeof(char*));