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 initialize my large 2D array to zero.
if i allocate memory through calloc it will automatically initialize all the cells to zero.
Whether it is possible to allocate memory for 2D array using single calloc function ?
Thank you
If you want to be able to access the matrix elements by using the [] operator, you'll have to first allocate an intermediate structure that contains pointers to the data stored on each row of the matrix.
Each row will be zeroed because they're allocated using calloc(). Is this what you're looking for?
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int **a;
unsigned int num_rows = 2000;
unsigned int num_columns = 190;
a = calloc(num_rows, sizeof(*a));
if (a == NULL) {
/* TODO: Error handling. */
return -1;
}
for (unsigned int i = 0; i < num_rows; i++) {
a[i] = calloc(num_columns, sizeof(**a));
if (a[i] == NULL) {
/* TODO: Error handling. */
return -1;
}
}
printf("%d\n", a[0][0]);
/* TODO: Free calloc'd memory. */
return 0;
}
int nrows = 2000, ncolumns = 190;
int **a=calloc(nrows * ncolumns, sizeof(a));
printf("%d", a[0][0]);
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 5 years ago.
Improve this question
Write a complete program.
The program should read two integers: m and n, from the keyboard.
Allocate memory for a dynamic 2D m * n array of doubles.
Initialize the array according to the formula A[i][j]=(i-5)/(j+1).
My code:
#include <stdio.h>
#include <math.h>
int main() {
int m,n;
scanf ("%d %d",&m &n);
double**A=(double**) malloc (m*size of (double*));
double*B=(double*) malloc (m*n * size of (double));
for (int i=0;i<n;i++){
A[i]=B+i*m;
}
for (int i=0;i<n;i++){
for (int j=0;i<m;j++){
A[i][j]=(i-5)/(j+1);
}
}
free (A);
free (B);
return 0;
}
Few things wrong:
size not defined.
#include <math.h> is not needed since you don't call any math functions.
Strictly speaking you should #include <stdlib.h> as this declares malloc() and friends.
A , is missing in scanf ("%d %d",&m &n);.
No need to cast malloc() return value.
Always start variable names with a small letter.
You have one } too many.
Indentation and code formatting is really bad and is asking for trouble.**
...
Check this section of the C-FAQ to see if you've done the allocation correctly.
Idea: Read through the C-FAQ mentioned above, it will teach you a lot and will turn out to be a valuable time investment.
**Here's an example of good code indentation & formatting (without fixes):
int main()
{
int m;
int n;
scanf("%d %d", &m, &n);
double** A = malloc(m * size of (double*));
double* B = malloc(m * n * size of (double));
for (int i = 0; i < n; i++)
{
B[i] = B + i * m;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; i < m; j++)
{
A[i][j] = (i - 5) / (j + 1);
}
}
free(A);
free(B);
return 0;
}
Well, I fixed the superfluous }.
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The purpose of this exercise is to use the two-subscript method of dynamic memory allocation.
Input for this program is a two-dimensional array of floating point data located in a file named
testdata2. The input array will contain 3 rows of data with each row containing 5 columns of data.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int temp;
int number;
int r = 3;
int c = 5;
fp = fopen("testdata2.txt", "r");
number = (int)malloc(r * c * sizeof(int));
while (fscanf(fp, "%d", &temp) != EOF){
for(int i = 0; i < 3;i++){
for(int j = 0; j < 5; j++){
temp = number[i][j];
}
}
}
return(0);
}
Among the plethora of things incorrect in your code (any one of which can result in undefined behavior):
The core data type is wrong. The question specifically calls for floating-point values, yet you're using integer types.
The receiver of any memory allocation in C should be a pointer; you're using a simple int.
You're hiding whatever warnings/errors you're receiving by hard-casting. Casting malloc in C isn't necessary, nor advised.
Even if everything else were fixed, your assignment statement for temp = ... is backward. You want to save the value just-read into your matrix, not throw it away and overwrite it with whatever undefined value resides in your memory-just-allocated.
All of that said, knowing the width of your array of arrays is five, the problem reduces to this. Note temp isn't needed at all
#include <stdio.h>
#include <stdlib.h>
int main()
{
static const size_t r = 3;
static const size_t c = 5;
FILE *fp = NULL;
double (*number)[c] = NULL; // pointer to array of dimension c.
fp = fopen("testdata2.txt", "r");
if (fp == NULL)
{
perror("Failed to open file: ");
return EXIT_FAILURE;
}
number = malloc(r * sizeof *number); // allocate r-rows of dimension c
if (number == NULL)
{
perror("Failed to allocate array of arrays: ");
return EXIT_FAILURE;
}
for (size_t i=0; i<r; ++i)
{
for (size_t j=0; j<c; ++j)
{
if (fscanf(fp, "%lf", number[i]+j) != 1)
{
fprintf(stderr, "Failed to parse int at %zu,%zu", i, j);
return EXIT_FAILURE;
}
}
}
for (size_t i=0; i<r; ++i)
{
for (size_t j=0; j<c; ++j)
printf("%lf ", number[i][j]);
fputc('\n', stdout);
}
free(number);
return(0);
}
You are declaring an integer:
int number;
and you are allocating memory with malloc assuming it is a multi-dimensional array, then trying to access its elements in the same way.
Change the declaration to:
int **number;
it is not
(int)malloc(rcsizeof(int))
It is
(int*) malloc(rcsizeof(int))
One more mistake is that you can't access the elements as
temp=number[i][j];
Replace it with
temp=number[i*r+j]
Hope this helps
number = (int)malloc(r * c * sizeof(int));
In C, never cast the result of a malloc. If you had left out the cast to int, you'd have a diagnostic here telling you that number is not a pointer type.
You can do this:
int* number = malloc(r * c * sizeof(int));
But that gives you one big single dimensional array. You would need to dereference it like this:
temp = number[i * c + j];
If you want two dimensional indices as if you had declared it like this:
int number[r][c];
you need to allocate it in two stages:
int** number = malloc(r * sizeof(int*));
number[0] = malloc(r * c * sizeof(int));
for (int i = 1 ; i < r ; i++)
{
number[i] = &number[0][i * c];
}
That sets up a big array of ints and an intermediate array of pointers to ints for each row. Now you can do
temp = number[i][j];
Edit
Or you can do what Dmitri says which is this:
int (*number)[c] = malloc(r * c * sizeof(number[0][0]));
That effectively mallocs an array of r blocks of c ints in one go.
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
The questions from my textbook is:
Write a function that returns a pointer to float and has two parameters: 1)a two dim array of floats with COL column and 2)an integer that represents the number of rows. Returned pointer should point to an array of floats containing the sum of the elements in the corresponding row of the 2 dim array.
My solution is:
float* ptr (float array[][COL], int rows) {
float *ptr;
int j;
for (j=0; j<COL; j++)
*ptr += array[rows][j];
return *ptr;
}
I just wonder whether this solution is correct? Thank you very much.
You've not allocated any memory for ptr to point at, so the answer is unavoidably wrong. You have to ensure that the memory will last long enough to be usable, so you can't return a pointer to an automatic array; you'll either have to have a static array (but how do you make it big enough), or you'll have to dynamically allocate the memory (malloc() et al) and then make sure the calling code frees what was allocated.
You also have algorithmic problems. You're accumulating all the values for all rows into a single value, whereas you're requested to calculate a separate value for each row.
Also, *ptr is a float; you'd need just return ptr; to have the types correct.
Your function name needs to be different, too.
#include <stdio.h>
#include <stdlib.h>
enum { COL = 7 };
float *row_sums(float array[][COL], int rows)
{
float *ptr = malloc(rows * sizeof(*ptr));
if (ptr != 0)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < COL; j++)
ptr[i] += array[i][j];
}
return ptr;
}
int main(void)
{
float data[][COL] = { { 1.0 }, { 2.0 }, { 0.0, 3.0 }, { -1.0, -2.0 } };
float *result = row_sums(data, 4);
for (int i = 0; i < 4; i++)
printf("%d: %.1f\n", i, result[i]);
free(result);
return(0);
}
The use of 4 is sub-optimal; it should be something like ROWS, where that's defined using:
enum { ROWS = sizeof(data) / sizeof(data[0]) } ;
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 I have the following code so far:
#include <stdio.h>
int foo (int *pointer, int row, int col);
int main() {
int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};
int *pointer= array[0];
int row = 2;
int col = 2;
int answer = foo (pointer, row, col);
printf("%d", answer); //prints 5 (which is wrong)
printf("%d", array[2][2]); //prints 9
}
int foo (int *pointer, int row, int col){ //I don't want to use any square brackets here, unless I really have to.
int value;
value = *((int *)(pointer+row)+col);
return value;
}
So my main issue is with passing a 2D pointer, please explain in detail as I am still new at coding. I don't want to really change what I am passing (as in I want to use the pointer in foo(pointer, row, col) and not foo (array, row, col).
passing a 2D pointer
From how you (ab)used the terminology, it's quite clear that you're under the wrong impression that pointers and arrays are the same. They aren't.
If you want to access a multidimensional array using pointers, you must specify all its dimensions (except the first, innermost one) and use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays are contiguous in memory:
const size_t h = 2;
const size_t w = 3;
int arr[h][w] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int *p = &arr[1][2];
int *q = arr[1];
int (*t)[3] = &arr[1];
printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);
return 0;
int *pointer= array[0];
Instead of use this
int *pointer= &array[0];
Or
int *pointer= array;