Arrays are contiguous blocks of memory. Since the name of the array is basically a pointer to the first element, you can use array notation to access the rest of the block. Remember, however, that C does not have error checking at the boundaries of the array, so if you leave the end of the memory block, you can do all kinds of things that you did not intend, and most likely some memory error or segmentation error. Since your int can be of variable size, I would use this code instead:
int *start; int i; start = malloc(40 * sizeof(int)); for (i = 0; i < 40; i++) { start[i] = 0; }
Something like this will work well. The way you do this, at least from the code you sent, there is no way to stop the loop, because as soon as it exceeds the memory block, it will continue to work until it starts in NULL or not get a memory error. In other words, the loop will only be completed if it is running at null. This zero may be within the block of memory that you allocated, or it may be outside the block.
EDIT: One thing I noticed about my code. It will allocate space for 40 ints, which may be 4 bytes, 8 bytes or something else depending on the architecture of the machine you are working on. If you REALLY want only 40 bytes of integers, then do something like this:
int *start; int i; int size; size = 40/sizeof(int); start = malloc(size); for (i = 0; i < size; i++) { start[i] = 0; }
Or you can use char or unsigned char data type if you need to. Another thing I noticed. The malloc function returns a void pointer type that is compatible with all pointers, so there is no need to do typecast on malloc.
Daniel Rudy
source share