Sunday, August 2, 2009

Pointer/Array Question?

Given the following definition:





int num[26] = {23, 3, 5, 7, 4, -1, 6};


int* pn;





write a test to check whether pn points beyond the end of num.





Please help me answer this question taken from my C programming textbook.

Pointer/Array Question?
Pointer arithmetic is a complicated topic of C/C++.





Basically, in C %26amp; C++, an array is a pointer to the memory location of the first element. All other elements in the array are located in memory right after the first element.





Pointer arithmetic is based on addition and subtraction of pointer values. Also, memory is incremental. When you add an integer "n" to a pointer "p" the result "pr" is a pointer of the same type as the original pointer and its value is a pointer to the memory location where the n-th element of the array pointed by "p" should be.





From your question, if you apply what I said, you can test if pn is pointing beyon the end of array num like this:





if (pn %26gt; num + 25)


{


// pn is pointing beyond end of array num


}


No comments:

Post a Comment