Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am declaring a 2d array in a headers file like this : int **arr;
Then I'm allocating memory and I initialize it with zeros.
However I'm getting segmentation fault.
Here is my code :
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
arr[u] = (int *)malloc(q * sizeof(int));
for(int i=0; i<d+1; i++)
{
for(int j=0; j<q+1; j++)
{
arr[i][j]=0;
}
}
d+1 and q+1 both outside the boundary.
Use d and q
If you want to initialize with zero use calloc() which is simple to use and reduces redundant operations
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
scoreBoard[u] = (int *)calloc(q , sizeof(int));
This code will create 2d int array and initialize with zero
You are getting a segmentation fault because you are overstepping the array's bounds.
for (int i = 0; i < d + 1; i++)
Should become:
for (int i = 0; i < d; i++)
And similarly for the other one. Don't forget array indices go from 0 to 1 less than the size (in elements) of the array.
Also:
Was the memory for scoreboard allocated? Currently, you create an array called arr rather than for the scoreboard you are initializing, so scoreboard[u] may also be out of bounds regardless of the value of u.
Related
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 1 year ago.
Improve this question
Suppose I get input from somewhere and store it in a variable. Pretend the variable is Cols.
I want to make an array in the form
int (*p)[Cols]
Now, I know you can't do this. So how would I dynamically allocate it to do it?
Teaching me how to do so would really be appreciated!
You can absolutely use int (*p)[Cols], it's a pointer to array of size Cols (Cols times size of int, in bytes), you just have to allocate memory for it, until you do, it doesn't point to a valid memory location. The constraint is that the allocated memory needs to be in blocks of multiples of Cols:
int (*p)[Cols] = malloc(sizeof *p); //prefered
Or
int (*p)[Cols] = malloc(sizeof(int) * Cols); //alternative
In both of the above expressions, supposing Cols's value is 10, p will point to a block of memory that can take 10 ints.
Usage:
for (int i = 0; i < Cols; i++)
{
p[0][i] = i;
}
The above expresssions only allocated space for one line of ints, but since p is a pointer to array, you can allocate space for as many of them as you want (given the memory constraints).
Let's assume you want an array with 5 lines and Cols columns:
int (*p)[Cols] = malloc(sizeof *p * 5);
Usage:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < Cols; j++)
{
p[i][j] = i * j;
}
}
As you (probably) know this kind of construct is primarily used to emulate a 2D array, one of the advantages is that you can then free all the memory with a single free:
free(p);
Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple frees.
int (*p)[Cols] = malloc( sizeof *p * Rows );
allocates enough space for a Rows x Cols array of int and assigns the address of that array to p. You can then access each element as p[i][j].
To deallocate all you need is
free( p );
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to define two dynamic 2-dimensional arrays using malloc and here is the code (I know that M = 118 and N = 186):
int **Cf;
Cf = (int **) malloc(M * sizeof(int *));
for (i = 0; i < N; i++)
Cf[i] = (int *) malloc(N * sizeof(int));
The array Cf allocates memory with no problem. However, my program crashes when it comes to Ct. I debugged the code and found out that Ct[i] = (int *) malloc(N * sizeof(int)) fails when N=164 which is kinda weird.
Key issue: Wrong range used. Should be <M, not <N. #xing
Recommend using sizeof against the referenced object than the type. Easier to code, review and maintain.
Note that the casts are not required. #Some programmer dude
int **Cf = malloc(sizeof *CF * M);
assert(Cf);
// M, not N
// for(i=0;i<N;i++){
for(size_t m=0; m < M; m++){
printf("%zu\n", m);
Cf[m] = malloc(sizeof *(Cf[m]) * N);
assert(Cf[m]);
}
Code also used m instead of i to help make clear that the m index goes with M.
To use calloc()
// int **Cf = malloc(sizeof *CF * M);
int **Cf = calloc(M, sizeof *CF);
// Cf[m] = malloc(sizeof *(Cf[m]) * N);
Cf[m] = calloc(N, sizeof *(Cf[m]));
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 want to define a 2D array with size 20*100000 in C. I do not want to keep the size fixed.
double **twod = malloc(20 * sizeof(double *));
int i;
if (twod == NULL)
abort();
for (i = 0; i < 20; ++i)
if ((twod[i] = malloc(100000 * sizeof(double))) == NULL)
abort();
// clean up
for (i = 0; i < 20; ++i)
free(twod[i]);
free(twod);
The first malloc call allocates space for 20 double pointers. Each double pointer will point to a subarray.
The second malloc call in the loop allocates 100000 doubles in each subarray.
The free calls do the inverse of malloc--they return memory to free store. First, each subarray must be freed, in a loop. Then the entire array itself must be freed too.
The return value of malloc is examined against NULL. If malloc returns NULL, then the system is out of memory. This is important since you are allocating HUGE amounts of memory. If malloc returns NULL, the application is aborted.
You'll need to define a pointer to pointer and initialize it like this:
int i;
double **array;
array = malloc(sizeof(double *)) * 20);
for (i=0; i<20; i++) {
array[i] = malloc(sizeof(double) * 100000);
}
Don't forget to free the memory when you're done with it.
You can use a Variable-length array (since C99) in order to avoid fragmentation:
double (*array)[cols];
array = malloc(sizeof(*array) * rows);
In this way calling free(array); is enough.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
well, i'm working in C. I want to make a function that return a matrix[][].
This is my function:
char **mapa(int largo,int ancho)
{
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
for(i = 0; i < largo; ++i)
{
matriz[i]= (char *)malloc(sizeof(char)*ancho);
}
for(i = 0; i < largo; i++)
{
for(j = 0; j < ancho; j++)
{
matriz[i][j] = 'k';
}
}
for(i = 0; i < largo; i++)
{
for (j = 0; j < ancho; j++)
{
printf("%c",matriz[i][j]);
}
}
return matriz;
}
Using gdb it give me this:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004008b8 in mapa (largo=10, ancho=10) at main.c:18
18 matriz[i][j] = 'k';
I don't know where the error is, if someone can give me a hand i'll be very gratefull.
Many thanks.
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
Your matriz variable is a pointer to an array of pointers, each of which points to an array of char. You first need to allocate memory for the array of pointers, which requires largo times the size of the pointers, which is sizeof (char *). You only allocate space for largo times the size of a single char.
The easiest way to get the allocation right is to use the following pattern:
p = malloc (n * sizeof *p);
In other words, allocate n times the size of whatever p points to. This will automatically allocate the right amount regardless of the type of p, assuming you get the n right. If you're declaring the pointer in the same line, it looks a little different:
T *p = malloc (n * sizeof *p); /* For some type T */
In this case there is an asterisk before p on both sides. This difference is something you will have to be aware of, especially when you have more than one level of indirection.
Your first allocation, using this pattern, would look like this:
matriz = malloc (largo * sizeof *matriz);
and the second:
matriz[i] = malloc (ancho * sizeof *matriz[i]);
Note, that you never have to cast a void pointer (the return value of malloc()), and that the argument to the sizeof operator only needs parenthesis when it's a type name. When you get rid of the parenthesis, and place the quantity (ancho) before the sizeof operator, the result is an expression that is very clean and easy to understand. That is, of course, my personal opinion.
Your first malloc casts to a pointer of pointer's but that doesn't mean it is. If you look at your 2nd malloc you're allocating the same thing. So when you dereference matriz[i][z] you're dereferencing a charater, not a pointer. So I believe, it's been a while since I've done C, your first malloc needs to be (char**)malloc(sizeof(char*)*largo).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've got some trouble about a C function.
This is the function:
int* CalcMeanPower(int Media[], int** MeanPowerArray, int righe, int colonne)
{
int i=0, k=0;
int ArrayPower[] = {0, 0, 0, 0};
for (i=0; i<righe; i++)
{
for (k=0; k<colonne; k++)
{
ArrayPower[k] = ArrayPower[k] + MeanPowerArray[i][k] ;
}
}
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
return Media;
}
This is how I call the function from the main:
VettoreMedia = CalcMeanPower(VettoreMedia, RefMeanPower, num_mean, N);
,where the variables are defined as follows:
int* RefMeanPower[N];
int* VettoreMedia;
int N=4, num_mean=5;
When I try to run the program it returns me a segmentation fault while trying to do:
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
Could you please explain me what I'm doing wrong? I've searched through the net but I can't find the answer. This function is only a little piece of my C program, but I'm sure it faults in this cycle!
Please Help..
u have not initialized VetorreMedia befor passing to the function. since this is not initialized,Media also is pointing to unknown location so segmentation fault. VetorreMedia should have some default value.
If you run this in a debugger you will see where your segfault is occurring and be able to solve it from there.
Google gdb cheatsheet to get started.
You need to reserve memory for your variables/arrays.
RefMeanPower is just a array of plain uninitialized pointers. And VettoreMedia is just a plain uninitialized pointer.
for(int i = 0; i < N; ++i)
RefMeanPower[i] = malloc(sizeof(int) * num_mean);
// don't forget to free after usage
for(int i = 0; i < N; ++i)
free(RefMeanPower[i]);
Where you get RefMeanPower[N][num_mean] so swap k and i as indices or N and num_mean on creation.
and for VettoreMedia you can do
VettoreMedia = malloc(sizeof(int) * N);
// don't forget to free after usage
free(VettoreMedia);
or
int VettoreMedia[N];
// frees automatically when leaving scope