Allocating array of struct pointers? [duplicate] - c

This question already has answers here:
malloc an array of struct pointers
(4 answers)
Closed 8 years ago.
I couldn't find answer of the exact question, since the condition is a bit more specific:
How can i allocate array of struct pointers.
typedef struct COORDS
{
int xp;
int yp;
} coord;
coord** xy;
i want to allocate it like: xy[500][460] But it returns invalid memory error when accessing them.

coord** new = malloc (500 * sizeof (coord*));
int idx = 0;
for(; idx < 500; ++idx)
new [idx] = malloc (460 * sizeof (coord));

Static allocation:
coord xy[500][460];
Dynamic allocation:
coord** xy = (coord**)malloc(sizeof(coord*)*500);
for (int i=0; i<500; i++)
xy[i] = (coord*)malloc(sizeof(coord)*460);
// and at a later point in the execution of your program
for (int i=0; i<500; i++)
free(xy[i]);
free(xy);

Related

C - Segmentation Fault Assigning value to Array of Struct

I am getting segmentation fault whenever I do this. I wonder if there is a way for me to assign a value to the struct without getting SegFault?
typedef struct _chunk
{
int lo; // lower bound
int hi; // higher bound
} chunk;
chunk_stack = (chunk **)malloc(10 * 10 * sizeof(chunk **));
for (i = 0; i < chunk_per_thread; i++)
{
chunk_stack[myid][i].lo = 0;
chunk_stack[myid][i].hi = 1;
}
Suppose you need to allocate a 2D array of size r * c.You need to first allocate memory for the double pointer which you did but have an error in it i.e., one extra * inside malloc function.
chunk **chunk_stack = (chunk **)malloc(r * sizeof(chunk *));
Then you need to allocate memory for each of the rows separately.
for(int i = 0; i < r; i++){
chunk_stack[i] = (chunk*)malloc(c * sizeof(chunk));
}

The purpose of a triple pointer in C [duplicate]

This question already has answers here:
Triple pointers in C: is it a matter of style?
(5 answers)
Closed 4 years ago.
While I have seen some threads on this, I fail to understand the meaning behind triple pointers, since it seems that it's possible to do the same without them.
void Reading(int *N, int ***M) {
printf("Input an integer N: \n");
scanf("%d", N);
*M = malloc(N * sizeof(int*));
int i;
for (i = 0; i < N; i++)
*(*M+i) = malloc(N * sizeof(int));
printf("Input N*N integers that will form a matrix \n");
int i, j;
for (i = 0; i < *N; i++)
for (j = 0; j < *N; j++)
scanf("%d", &((*M)[i][j]));
}
This code makes **M a 2D array. If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore. Could someone please explain why this is the case ?
If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore.
There are two ways to pass a variable to a function: either by value or by reference. When you pass the reference of a variable, that allows you to modify it.
Example:
void fun(int a) {
a = 42; // Does nothing
}
int b = 9;
fun(b);
// b is unchanged.
void fun(int *a) {
*a = 42;
}
int b = 9;
fun(&b);
// b equals 42.
Your variable happens to be a of type int **, when you pass the address (reference) of this variable, this makes it a int ***.

Free dynamic memory with free() [duplicate]

This question already has an answer here:
free 2d array in c
(1 answer)
Closed 5 years ago.
#include <stdlib.h>
#include <stdio.h>
int main() {
char **last_names;
// last_names has been assigned a char * array of length 4. Each element of the array has
// been assigned a char array of length 20.
//
// All of these memory has been allocated on the heap.
// Free all of the allocated memory (hint: 5 total arrays).
return 0;
}
I know the free() method and this is my approach;
free(*last_names);
free(last_names);
but it's not true. Any help will be appreciated
Guessing from your description of the code, your memory allocation would be:
last_names = malloc(4 * sizeof(char*));
for (int i = 0; i < 4; i++)
last_names[i] = malloc(20 * sizeof(char));
So deallocation should be done as follows:
for (int i = 0; i < 4; i++)
free(last_names[i]);
free(last_names);

Passing a 2d array as a pointer C [duplicate]

This question already has answers here:
C, passing 2 dimensional array
(2 answers)
Closed 9 years ago.
So I have a recursive function that requires it to be of type void, without turning to global variables how can I pass a 2d array as a pointer and dereference once I edit values in the recursive function? I already tried int * m[10][10], I can't show all of the code since it is an assignment, pointers aren't required in the assignment but global variables are not permitted
Void h(int * m[10][10]){
int x = 5;
int y = 5;
*m[x][y]=7;
}
That's the general idea
Simply try this
Void h(int m[][10]) {
...
m[x][y]=7;
}
Call your function either as
h(&m[0]); // Passing the address of first row of 2D array m.
or
h(m); // As array names decays to pointer to first element of the array. Note that
// m will decays to pointer to m[0], not m[0][0].
It all depends on how you declared the array supposed to be passed to your function.
If you declared it like this
int my_array[10][10]; // array declaration
then
void fun (int m[10][10]); // prototype of a function accepting my_array
fun (my_array); // calling the function
is what you are looking for.
In that case, m is a constant pointer to 100 contiguous ints that are accessed as a 10x10 2D array.
Other possible variant:
int * my_array[10];
for (i = 0 ; i != 10 ; i++) my_array[i] = malloc (10*sizeof(int));
void fun (int m[10][]); // these syntaxes are equivalent
void fun (int * m[10]);
or this one:
int ** my_array;
my_array = malloc (10 * sizeof (int*));
for (i = 0 ; i != 10 ; i++) my_array[i] = malloc (10*sizeof(int));
void fun (int m[][]); // these syntaxes are equivalent
void fun (int * m[]);
void fun (int ** m);
or this pathological one:
int (* my_array)[10];
int a0[10];
int a1[10];
/* ... */
int a9[10];
my_array = malloc (10 * sizeof (int *));
my_array[0] = a0;
my_array[1] = a1;
/* ... */
my_array[9] = a9;
void fun (int m[][10]); // these syntaxes are equivalent
void fun (int (* m)[10]);
If your variable declaration and function prototype are not consistent, you will not access the array properly from within your function, read incoherent values, and mess up your memory and possibly crash if you attempt to modify an element.
If you have nothing better to do, you can read this little essay of mine on the subject for further details.
void h(int** m) {
int x = 5;
int y = 7;
m[x][y] = 7;
}
int main(int argc, char* argv[])
{
int** a = (int **)malloc(10*sizeof(int *));
for (int i=0; i<10; i++) {
a[i] = (int *)malloc(10*sizeof(int));
}
h(a);
return 0;
}

How can I get an array and count with variable size by a function? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I want to use a C function to get an array and count with variable size (#runtime). I implement this function as following:
void getList(int **listArray, int *count){
// get the total count
int totalListCount = getTotalListCount();
// Initialize the array
int theList[totalListCount];
memset( theList, 0, sizeof(int)*totalListCount );
// Set the elements in the array
for (int i = 0; i < totalListCount; i++) {
theList[i] = theElementAtIndex(i);
}
// Assign the value to the pointer.
*count = totalListCount;
*listArray = theList;
}
After getting the array and the count, I could print the values:
int *list;
int count;
getList(&list, &count);
for (int i = 0; i < count; i++) {
printf("list[%d]: %d \n", i, list[i]);
}
Is the implementation correct? Do I need to manage the memory for those pointers, and how?
// Initialize the array
int theList[totalListCount];
you should not return the function's local array, you should use malloc like this:
int *theList = malloc(totalListCount);
off course,you should free it when you not use it

Resources