Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you iterate through a pointer?

Tags:

c

pointers

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.

like image 501
svsav Avatar asked Apr 28 '15 02:04

svsav


People also ask

How do you iterate through a pointer to an array?

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.

How can a pointer be used to access individual elements of an 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.

What are the pointers in C language?

A pointer is a variable that stores the memory address of another variable as its value.


2 Answers

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"

like image 153
fkl Avatar answered Sep 23 '22 12:09

fkl


First of all, you should be allocating ints 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++ ;
}
like image 33
2501 Avatar answered Sep 21 '22 12:09

2501