Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is there a best way to create an array of structs that resides in the heap with malloc? Specifically if I create the array initially on the heap but wont be able to create each of the entries upfront, I'd still like to be able to create the struct/entries and have them reside in the heap and be accessible from the struct. Is there a good/canonical way to do this?
If your structures are allocated on the heap, you can declare and allocate an array of pointers to each structure on the heap as well:
struct my_struct **struct_arr = malloc(sizeof(struct my_struct *) * ARR_LEN);
Where ARR_LEN is the number of structures you would like to store in the array. In that case,
struct_arr[0]
is of type *struct my_struct (pointer to my_struct).
So now, you can allocate a my_struct structure in heap memory, like this:
struct my_struct *struct_ptr = malloc(sizeof(struct my_struct));
and store the resulting pointer into the array of structures above:
struct_arr[0] = struct_ptr;
To allocate memory is through the malloc / realloc / calloc. It is not the only way to do it, but this is the ISO C standard compliance.
In terms of accesing, it is not defined by where the variable is being allocated (stack, heap or wherever), it is defined by the scope of the way to access to the bunch of memory (to determine the scope you can use the keyword volatile, local variables, etc).
Regarding structs, you will have to "reserve" an amount of memory big enough to allocate the array. Once you get the pointer to the reserved bunch of memory, you are able to use it (in that case, for your struct), something like:
struct structType {
int varA;
};
struct structType *structP = malloc(sizeof(struct structType));
structP->varA = 1;
Related
This question already has answers here:
Can we have a struct element of type Variable length array? [duplicate]
(5 answers)
Closed 2 years ago.
I would like to define array size inside a structure by using a parameter of this structure. Does C permit to do something like this ?
struct queue {
int head;
int top;
int size;
struct action action[size];
};
No you can't. Since action is not a dynamic variable, the compiler needs to know at compile time how much space it needs for action. size was not even initialized. Anyway, you could see this just by trying to compile.
The size is not known at the time of defining the struct. Therefore it is impossible for the compiler to understand how large the result will be. Typically, you would first allocate memory for the struct, and have a struct action *action; member. After initializing the struct, you use instance->action = calloc(instance->size, sizeof *instance->action) to allocate memory for the array.
This question already has an answer here:
Segmentation Fault, large arrays
(1 answer)
Closed 4 years ago.
So I'm trying to declare a struct of size 19,000, however when I compile this I get Seg fault, core dumped. I think I have to use malloc but I can't
figure out whats the best syntax to use considering I'm not using pointers!!
Struct people{
char name[100]
char secondname[100]
}
int main(){
struct people p1[19000]
}
Above is the code corresponding to my problem
Any Help would be greatly appreciated
Your struct array requires about 3.8Mb of stack space, while on most modern Desktop platforms, the typical default process or thread stack is perhaps a couple of Mb.
You can either dynamically or statically allocate the memory. Static allocation if simplest and appropriate is the lifetime of the array is the duration of program execution, and the required size is known a priori.
int main()
{
static struct people p1[19000] ;
}
Dynamic allocation is a possible solution, but since malloc() returns a pointer to the allocated memory, you are necessarily using pointers; but array access notation can be used, so your exposure ot pointers will be minimal:
int main()
{
struct people* p1 = malloc(sizeof(struct people) *19000 ) ;
...
// Access to elements of the dynamically allocated array
// is identical to that of the statically allocated array.
printf( "%s", p1[0].name ) ;
}
An advantage of dynamic allocation is that you can avoid allocating an arbitrarily large space, and create records on demand, storing pointers in a dynamically resizing array (using realloc() for example), or some suitable container data structure such as a linked list. But perhaps that is too advanced for where you are at at the moment.
struct people p1[19000] tries to create 19000 structs of 100+100 bytes in automatic stack memory. Normal stack memory is not large enough and you get a stack overflow or some other error.
In C, there is much more heap memory available, but the programmer has to do the heap memory management
To allocate the array in heap memory, you can use for instance:
int main() {
struct people *p1 = malloc(19000 * sizeof(struct people));
// you can now access p1 using array brackets as follows:
// strcpy(p1[0].name, "name");
// strcpy(p1[0].secondname, "secondname");
// printf("name: %s, secondname: %s\n", p1[0].name, p1[0].secondname);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I declared an array in C of size 150X150X150. Upon compiling the program to get an array of same size,the compiler gave no errors or warnings. but when I tried running it, the program stops responding.
void main(){
int i,j,k;
char giv[150][150][50],tar[150][150][50];
for(int i=0;i<150;i++)
{
for(j=0;j<150;j++)
{
for(k=0;k<50;k++)
cin>>giv[i][j][k];
}
}
}
Is there any way that I can create an array of 150*150*150 without causing a run time error?
EDIT: I know multidimensional arrays work. This is not a compilation error. Its a run time error, whose cause was I am not able to pinpoint.
You just declared two arrays on the stack.
Each array has size: 150 * 150 * 50 bytes, or about 1.1MB.
So you are asking for 2.2MB from the stack.
Typical stack size is about 1 or 2MB.
So I expect you're getting a StackOverflow Exception.
(kinda appropriate for this site)
You could allocate the arrays on the heap:
#include <stdlib.h> /* for malloc()/calloc() */
#include <stdio.h> /* for perror() */
...
char (*pgiv)[150][150][50] = malloc(sizeof *giv);
char (*ptar)[150][150][50] = malloc(sizeof *tar);
If you want to have the arrays' elements initialised to all 0s on allocation use calloc() as follows:
char (*pgiv)[150][150][50] = calloc(1, sizeof *giv);
char (*ptar)[150][150][50] = calloc(1, sizeof *tar);
Also test wether the allocation succeed or not:
if (NULL == pgiv)
perror("malloc() failed");
if (NULL == ptar)
perror("malloc() failed");
Address an element by doing for example:
(*pgiv)[0][1][2] = 123;
Note that pgiv and ptar are actually pointers (to an array). That's why they need to be dereferenced (using the dereference operator *) before being used like an array.
It seems that the problem is with the limit of the stack memory.
In C++ you could use for example standard container std::vector.
In C you could allocate these arrays yourself dynamically.
The simplest way is either to declare these arrays globally that is outside any function or specify keyword static that the arrays had static storage duration. For example
static char giv[150][150][50],tar[150][150][50];
As for other languages then for example Java and C# allocate arrays in the managed heap. It keeps in the stack only a reference to the array.
This is my structure:
typedef struct wyraz{
char *slowo;
char *tlumaczenie;
struct wyraz *nastepny;
}WYRAZ;
typedef struct lista_tlumaczen{
char znak;
WYRAZ *lista_znakowa;
}LISTA_TLUMACZEN;
I want to have something like that
LISTA_TLUMACZEN tab[5];
but dynamic allocation I don't know how to do this, can someone help me?
When you have embedded pointers to structures you need to think of memory allocation in layers. Starting at the highest level first in this case works best. So start with:
LISTA_TLUMACZEN tab[5];
Here you're saying you want a table of pLISTA_TLUMACZEN structures. If you want this to be dynamic, then you need a pointer to a LISTA_TLUMACZEN:
LISTA_TLUMACZEN *tab;
Then to allocate it, you need to determine how big it is. In this case, we'll say NUMBER_OF_ELEMENTS:
tab = (LISTA_TLUMACZEN *)malloc(sizeof(LISTA_TLUMACZEN) * 5);
If you want to be especially safe that the malloc parameter isn't out of range you can use:
tab = (LISTA_TLUMACZEN *)(NUMBER_OF_ELEMENTS <= (SIZE_MAX / sizeof(LISTA_TLUMACZEN)) ? malloc(sizeof(LISTA_TLUMACZEN) * 5) : NULL);
Now we have the dynamically allocated equivalent of your tab[5] data declaration. Note that it's a table of LISTA_TLUMACZEN structures. So the amount of memory to allocate is the product of 5 and the size of the structure.
Your LISTA_TLUMACZEN structure also has a pointer to another structure with more pointers. You can allocate those following the same kind of logic or actually only as needed when the program needs them and freeing them when they're no longer needed (which is the reason for having dynamic allocation). If all you do is pre-allocate everything with malloc then there's no point and you may as well statically declare everything.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So what i am trying to do is have an array of lists, here is my code:
typedef struct stackList{
List * list;
} stack;
int main(){
int x;
stack ** stackTable;
for(x=0;x<100;x++)
stackTable[x]=malloc(sizeof(stack*)*100);
}
i get a segmentation fault on the for loop, i would assume the way i am trying to use the struct is wrong. Would i rather in the defintion of the struct use List ** list;
or is there a way to use it the way i am trying to use it
You get segmentation fault because you're accessing stackTable while it is uninitialized. You can't know to what address of memory it points, and you haven't allocated an array to hold the pointers that you are dereferencing.
You need to make stackTable point to a valid array of pointers, in this case I think is convenient to make it be an array:
Stack* stackTable[100];
Now you have an array of pointers to Stack, you can initialize them.
If instead you have just temporarily an array large 100, and you need to make it grow in future, that's how dynamically allocating it:
Stack** stackTable= malloc(100*sizeof(Stack*));
Before trying too hard to play with pointers and dynamic memory I might suggest writing some basic programs using basic 2d arrays. For instance:
char array2d[10][10];
Once you're confortable inserting elements into this array, extracting elements, etc, you can apply all of the same principles to any type.