Download presentation
Presentation is loading. Please wait.
Published byAllyson Hunter Modified over 8 years ago
1
Array of pointers We can have an array whose members are pointers, in this example pointers-to-int. int* data[3]; int i; int x = 5; int y = 89; int z = 34; data[0] = &x; data[1] = &y; data[2] = &z; for(i = 0; i < 3; i++) printf("%d\n", *data[i]);
2
#include int main() { printf("The address of the string is %p.\n", "apple"); printf("The length of the string is %d.\n", strlen("Hello")); return 0; } Output: The address of the string is 00415744. The length of the string is 5. Press any key to continue...
3
Passing the address after the last elements in the array #include int sump(int * start, int * end); int main(void) { int marbles[] = {20, 14, 23, 54}; int answer; answer = sump(marbles, marbles + 4); printf("The sum of integers in marbles is %d.\n", answer); return 0; } int sump(int * start, int * end) { int total = 0; while(start < end) { total += *start; start++; } return total; }
4
2D Array int score[4][2]; score, being the name of an array, is the address of the first element of the array. The first element of score is an array of two integers, so score is the address of an array of two integers. ▫That is score has the same value as &score[0]. Since score[0] is itself an array of two integers, so score[0] has the same value as &score[0][0], the address of its first element. Physically, both score and score[0] have the same address location.
5
2D Array Adding 1 to a pointer or address yields a value larger by the size of the object referred to. In this respect, score and score[0] differ, because score refers to 4 arrays containing two integers each. score[0] refers to one array of 2 integers. Therefore, score + 1 has a different value from score[0] + 1.
6
2D Array #include int main(void) { int score[4][2] = {{0,1},{2,3},{4,5},{6,7}}; printf("The value of score is %p.\n", score); printf("The value of score[0] is %p.\n", score[0]); printf("The value of &score[0][0] is %p.\n", &score[0][0]); printf("The value of score+1 is %p.\n", score+1); printf("The value of score[0]+1 is %p.\n", score[0]+1); return 0; }
7
Output The value of score is 0012FF44. The value of score[0] is 0012FF44. The value of &score[0][0] is 0012FF44. The value of score+1 is 0012FF4C. The value of score[0]+1 is 0012FF48. Press any key to continue...
10
References for pointers http://home.netcom.com/~tjensen/ptr/pointers.htm http://boredzo.org/pointers/
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.