how to initialize and use a 2d struct in c [closed] - c

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.

Related

C array of structs in malloc [closed]

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;

C: Two Different Arrays Pointing to the Same Struct [closed]

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 6 years ago.
Improve this question
I am working on a problem where I have a "master array" of pointers to a typedef struct programs. For each item/structure that I create, I allocate memory to a programs* temp variable and store it into an array programs* master_array[x].
However, my problem requires me to handle errors in the master_array where if a program goes into a "blocked" state, then I have to manage that(those) process(es) separately.
I want to create a second array called programs* blocked_array[y] and store programs that are blocked in there. In this case, I can have two arrays pointing to the same program. However, when I am finished with handling a program in blocked, how can I deallocate it/dereference the blocked_array[y]'s pointer to that program without impacting the master_array[x]'s pointer?
Do I create an empty program temp, not allocate memory to this temp program and make the blocked_array[y] point to that temp program to effectively, empty out blocked_array?
Would this create some sort of unintended consequence or does doing this stop the blocked array from pointing to it while preserving the master_array[x]'s pointer? Any thoughts would help, thanks.
You can simply add a bool isBlocked; field in your struct programs, and then you can handle this with a single array by
if(master_array[x]->isBlocked)
{
// Do something
}
else
{
// Do something else
}
Alternatively, you can use another array to store "isBlocked" information:
bool isBlocked[sizeof master_array / sizeof master_array[0]] = {0};
...
isBlocked[x] = true;
...
if(isBlocked[x])
{
// Do something
}
else
{
// Do something else
}

Easy way to deal with free in an array [closed]

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 6 years ago.
Improve this question
When I have a function that gets a pointer int *vector with a couple int values. I want to delete element number n. So I will use free() on that element. The problem I have now that there is a "hole" in my array of int values. Is there an easy way that I dont have this problem or do I really have to make a new int pinter and reorder my vector?
Given a function of this form:
void delete_element(int *vector, size_t index) {
// ...
}
The actual argument corresponding to vector is expected to be a pointer to a series of one or more (implied: index + 1 or more) contiguous ints. This could be part or all of an ordinary int array, or it could be a dynamically allocated block. If the former, then you cannot free any part of the space at all. If the latter, then you can free or reallocate the whole space, but not just the part associated with one element.
To avoid the deletion leaving a hole in your array, you need to move the later elements down, and to do that, you need to know how many elements there are in total. Therefore, you need a more informative function signature, perhaps something like this:
void delete_element(int *vector, size_t *size, size_t index) {
// ...
}
The actual deletion might involve simply using memmove() to move the later elements (overwriting the one to be deleted), and then decrementing the size. With respect to the latter, note that I suggest passing a pointer to the vector size, so that the function can modify the caller's copy.
If you want also to shrink the allocation then you need to do a bit more work (involving calling realloc(), and communicating the revised value of vector back to the caller), but note that in that case your function will not work on ordinary arrays.
There is no way to free() part of a block returned by malloc(). If you want to delete record[n], you need to copy record[n+1]...record[last] into the array.
If you really need to free() each element, you must first malloc() each element.

Is this array possible in C? Is there any other way for it? [closed]

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.

How to edit the index of a pointer array? [closed]

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
Ok so I am curious as to how you would go about using a pointer array to access a value in the index. Like for example:
printf("%c", (*character)[0]);
I know I have this code wrong, but I have know clue how to fix it. Say I want to access the 0 position in the pointer array and then print it like above, how would I do it?
Assuming character is char character[] = {'1'};
character[someIndex] means someIndex[character] means *(character+someIndex)
If that is what you wanted to know. So you should be doing something like:
printf("%c", *(character+0));
Which is equivalent to
printf("%c", *character);
printf("%c", character[0]);
Just missed out - regarding this statement
index of a pointer array?
Please know Arrays are not Pointers. If that is where you were confused.
From your question I observe that you have declare a character pointer something like this
char *character="something";
and now you want access its contents by indexing.
So why worrying,No matter whether you have declare pointer array or array.You can access its contents by any of following way:-
printf("%c",character[1]); //general method
or by pointer notation
printf("%c",*(character+1));
or
printf("%c",*(1+character));//commutative law
or more surprisingly you can use following method too
printf("%c",1[character]);
char *arr[20]={"Stackoverflow"};
This means you have an char type pointer array where 20 memory location's addresses are stored in an 20 size array. 1st memory location in arr[0] points to the string "Stackoverflow" and rest of them are not assigned(so you will get garbage value or maybe segmentation fault). Now, if you want to access 0th memory location just do this:
printf("%s\n",arr[0]);

Resources