I created a dynamic array ,and i need to initialize all the members to 0.
How can this be done in C?
int* array;
array = (int*) malloc(n*sizeof(int));
In this case you would use calloc():
array = (int*) calloc(n, sizeof(int));
It's safe to assume that all systems now have all zero bits as the representation for zero.
ยง6.2.6.2 guarantees this to work:
For any integer type, the object representation where all the bits are
zero shall be a representation of the value zero in that type.
It's also possible to do a combination of malloc() + memset(), but for reasons discussed in the comments of this answer, it is likely to be more efficient to use calloc().
memset(array, 0, n*sizeof(int));
Or alternatively, you could allocate your block of memory using calloc, which does this for you:
array = calloc(n, sizeof(int));
calloc documentation:
void *calloc(size_t nmemb, size_t size);
The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. ...
Use calloc function (usage example):
int *array = calloc(n, sizeof(int));
From calloc reference page:
void *calloc(size_t nelem, size_t elsize);
The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.
memset(array, 0, n * sizeof *array);
for (i=0; i<x; ++i){
array[i]=0;
}
That should do the trick. I guess you have to make a loop that makes 0 every element in the array. Memset could also work for you.
Related
I want to create dynamic array in the heap using malloc.
int *c = malloc(5 * sizeof(int));
The problem is that it is not initialized by zero and I'd like avoid using calloc as much as I can since I don't know how safe it is.
If I use calloc, is it going to do the same malloc job?
malloc():
malloc() takes one arguement: the amount of bytes to be allocated. The allocated bytes are uninitialized. Hence, their values could be anything from 0-255, or any combination of those numbers. Don't count on anything!
Code Sample:
int *mem = malloc(5 * sizeof(int));
calloc():
calloc() takes two arguements: the amount of elements to allocate memory for and the amount of memory that needs allocated for each element. It initializes each byte to zero.
Code Sample:
int *mem = calloc(5, sizeof(int));
From The C programming Language ~ Brian W. Kernighan and Dennis M. Ritchie:
void *calloc(size_t nobj, size_t size)
calloc returns a pointer to space for an array of nobj objects,
each of size size, or NULL if the request cannot be satisfied.
The space is initialized to zero bytes.
[Emphasis mine]
Alternatively, you can initialize memory with memset()
#include <string.h> // for memset()
//allocate memory
int *mem = malloc(5 * sizeof(int));
//initialize memory to zeros
memset(mem, 0, 5 * sizeof(int));
You can use calloc(), it's safe or else why would it be implemented in the standard library and how? It will be presumably more efficient than malloc() + memset() for large allocations.
You can use memset if you want to avoid using calloc for some reason. you can do it like this:
memset (c, 0, 5 * sizeof(int));
Don't forget to check the return value from malloc.
I want to allot memory dynamically for a 2D array.
Is there any difference between these two ?
1)
array = (int**)malloc(size * sizeof(int*));
for (i = 0; i < size; i++) {
array[i] = (int *) malloc(size * sizeof(int));
}
2)
array = (int**)malloc(size *size* sizeof(int));
If yes, what is better to use and why ?
In the first case
array = (int**)malloc(size * sizeof(int*));
for (i = 0; i < size; i++) {
array[i] = (int *) malloc(size * sizeof(int));
}
you are allocating size extents of the size equal to size * sizeof( int ) That is you are allocating size one-dimensional arrays. Accordingly you are allocating size pointers that point to first elements of these one-dimensional arrays.
In the second case expression
(int**)malloc(size *size* sizeof(int))
means allocation of an extent of size * size of objects of type int and the returned pointer is interpretated as int **. So this expression has no sense independing on what is placed in the left side of the assignment. take into account that the size of pointer can be greater than the size of int.
You could write instead
int ( *array )[size] = ( int (*)[size] )malloc(size *size* sizeof(int));
In this case you are indeed allocating a two dimensional array provided that size is a constant expression.
Those two solutions are very different. The first will give you a vector of pointers to vectors. The second will give you a vector of the requested size. It all depends on your use case. Which do you want?
When it comes to releasing the memory, the first can only be freed by calling free for each pointer in the vector and then a final free on the vector itself. The second can be freed with a single call. Don't have that be your deciding reason to use one or the other. It all depends on your use case.
What is the type of the object you want to allocate? Is it an int **, an int *[] or an int[][]?
I want to allot memory dynamically for a 2 dimensional array.
Then just do
int (*arr)[size] = malloc(size * sizeof *arr);
Is there any difference between these two ?
Yes, they are wrong because of different errors. The first attempt does not allocate a 2D array, it allocates an array of pointers and then a bunch of arrays of ints. Hence the result will not necessarily be contiguous in memory (and anyway, a pointer-to-pointer is not the same thing as a two-dimensional array.)
The second piece of code does allocate a contiguous block of memory, but then you are treating it as if it was a pointer-to-pointer, which is still not the same thing.
Oh, and actually, both snippets have a common error: the act of casting the return value of malloc().
I have the doubt if calloc initialize to zero all of the elements of a struct array like:
#define MAXDATA 10
struct Est2 {
int dato0; // Index k
int dato1; // Index j
int dato2; // Index i
double dato3; // Y Coordinate
};
Est2 *myArray = (Est2*) calloc(MAXDATA, sizeof(Est2));
I'm asking this because I don't want the initial data of myArray have garbage or Is there a problem if I don't initialize the array with any value if later in the code I will initialize it anyway for example storing the result of some arithmetical operations? Thanks in advance.
From man calloc:
void *calloc(size_t count, size_t size);
The calloc() function contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero.
calloc() guarantees that it's going to be pointing at zeroed data.
All of the bytes in the structure are set to 0.
This means that the ints have value 0. The double could be a trap , although most common systems use IEEE 754 representation for double, in which the value would be 0.0.
In this code, the "array" is an array of pointers to chars? Or something else?
struct tmep{
char (*array) [SIZE];
}
Thanks in advance :)
It's a pointer to an array of SIZE chars.
Declaration mimics use, so you evaluate the parenthesis first, (*array) gives you a char[SIZE].
To allocate, the stable version is as usual
array = malloc(num_elements * sizeof *array);
to specify the size of each object (char[SIZE] here) in the block by taking the sizeof the dereferenced pointer. You don't need to change that allocation if the type changes e.g. to int (*)[SIZE].
If you want to specify the type,
array = malloc(num_elements * sizeof(char (*)[SIZE]));
This allocates - if malloc succeeds - a block large enough for num_elements arrays of SIZE chars, each of these arrays is accessed with
array[i]
and the chars in the arrays in the block with
array[i][j]
I have dynamically allocated 2D array.
Here is the code
int **arrofptr ;
arrofptr = (int **)malloc(sizeof(int *) * 2);
arrofptr[0] = (int *)malloc(sizeof(int)*6144);
arrofptr[1] = (int *)malloc(sizeof(int)*4800);
Now i have to know that how many bytes are allocated in arrofptr,arrofptr[0],arrofptr[1]?
is there any way to know the size?
if we will print
sizeof(arrofptr);
sizeof(arrofptr[0]);
sizeof(arrofptr[1]);
then it will print 4.
You can't find size of arrofptr, because it is only a pointer to pointer. You are defining an array of arrays using that. There's no way to tell the size information with only a pointer, you need to maintain the size information yourself.
The only return value you get from malloc() is a pointer to the first byte of the allocated region (or NULL on failure). There is no portable, standard, way of getting the associated allocation size from such a pointer, so in general the answer is no.
The C way is to represent arrays and buffers in general with a pair of values: a base address and a size. The latter is typically of the type size_t, the same as the argument to malloc(), by the way.
if you want to keep track of the size of an allocated block of code you would need to store that information in the memory block that you allocate e.g.
// allocate 1000 ints plus one int to store size
int* p = malloc(1000*sizeof(int) + sizeof(int));
*p = (int)(1000*sizeof(int));
p += sizeof(int);
...
void foo(int *p)
{
if (p)
{
--p;
printf( "p size is %d bytes", *p );
}
}
alt. put in a struct
struct
{
int size;
int *array;
} s;
You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.
In your test case above sizeof is returning the size of the pointer, and thus your calculation the size of the pointers is usually 4, this is why you got 4 and is likely to have the trivial result of 4, always.