For example:
int *start;
start = (int*)malloc(40);
If I wanted to iterate through all 40 bytes, how would I do so? I tried doing something like:
while(start != NULL){
start++;
}
but that iterates through a massive number of values, which is much greater than 40. Thus, how do you ensure that you iterate through all 40 bytes.
Thanks for all the help.
This is done as follows. int *ptr = &arr[0]; After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array.
Access Array Elements Using Pointers In this program, the elements are stored in the integer array data[] . Then, the elements of the array are accessed using the pointer notation. By the way, data[0] is equivalent to *data and &data[0] is equivalent to data.
A pointer is a variable that stores the memory address of another variable as its value.
There are two issues here.
A single ptr++
skips as many bytes as the type of element it points to.
Here the type is int
, so it would skip 4 bytes each time (assuming a 32 bit machine since integer is 4 bytes (32 bits) there).
If you want to iterate through all 40 bytes (one byte at a time), iterate using say a char
data type (or type cast your int*
to char*
and then increment)
The other problem is your loop termination.
There is no one putting a NULL
at the end here, so your loop would keep running (and pointer advancing forward) until it runs into may be a null or goes out of your allotted memory area and crashes. The behavior is undefined.
If you allocated 40 bytes, you have to terminate at 40 bytes yourself.
Update:
Based upon a comment cum down vote to the original question, it is worth mentioning that type casting the result of malloc is not a good idea in C. The primary reason is that it could potentially tamper a failed allocation. It is a requirement in C++ though. The details can be found in the exact same question on SO. Search "casting return value of malloc"
First of all, you should be allocating int
s correctly:
int* start = malloc( sizeof( int )*40 ) ;
Then you can use array subscripting:
for( size_t i = 0 ; i < 40 ; i++ )
{
start[i] = 0 ;
}
or a pointer to the end of the allocated memory:
int* end = start+40 ;
int* iter = start ;
while( iter < end )
{
*iter= 0 ;
iter++ ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With