c - How do you iterate through a pointer? -


for example:

int *start; start = (int*)malloc(40); 

if wanted iterate through 40 bytes, how so? tried doing like:

while(start != null){      start++; } 

but iterates through massive number of values, greater 40. thus, how ensure iterate through 40 bytes.

thanks help.

there 2 issues here.

a single ptr++ skips as many bytes type of element points to.

here type int, skip 4 bytes each time (assuming 32 bit machine since integer 4 bytes (32 bits) there).

if want iterate through 40 bytes (one byte @ time), iterate using char data type (or type cast int* char* , increment)

the other problem loop termination.

there no 1 putting null @ end here, loop keep running (and pointer advancing forward) until runs may null or goes out of allotted memory area , crashes. the behavior undefined.

if allocated 40 bytes, have terminate @ 40 bytes yourself.

update:

based upon comment cum down vote original question, worth mentioning type casting result of malloc not idea in c. primary reason it potentially tamper failed allocation. requirement in c++ though. details can found in exact same question on so. search "casting return value of malloc"