In this chapter, we continue to explore the advanced topic of pointers.
1. Character pointer
General use:
int main()
{
char ch = 'w';
char *pc = &ch;
*pc = 'w';
return 0;
}
Code const char* pstr = "hello bit."; It's very easy for students to think that they put the string hello bit into the character pointer pstr, but / in essence, they put the string hello bit The address of the first character is placed in pstr.
int main() { //int a = 10; //printf("%p\n", &a); //char ch = 'w'; //char* p = &ch; const char* p = "abcdef"; //*p = 'w'; return 0; }
#include <stdio.h> int main() { char str1[] = "hello bit."; char str2[] = "hello bit."; const char* str3 = "hello bit."; const char* str4 = "hello bit."; if (str1 == str2) printf("str1 and str2 are same\n"); else printf("str1 and str2 are not same\n"); if (str3 == str4) printf("str3 and str4 are same\n"); else printf("str3 and str4 are not same\n"); return 0; }
int main() { char arr1[] = "abcdef"; char arr2[] = "abcdef"; const char* str1 = "abcdef"; const char* str2 = "abcdef"; if (arr1 == arr2) printf("arr1==arr2\n"); else printf("arr1!=arr2\n"); if (str1 == str2) printf("str1==str2\n"); else printf("str1!=str2\n"); return 0; }
The final output here is:
Here, str3 and str4 point to the same constant string. C/C + + will store the constant string in a separate memory area when several pointers. When pointing to the same string, they actually point to the same block of memory. However, when initializing different arrays with the same constant string, different memory blocks will be opened up. So str1 and str2 are different, and str3 and str4 are different.
2. Pointer array
ypedef int* pint; #define PINT int* int main() { //int a, b;//a int b int //int *pa, pb; pa -> int* pb -> int //int * pa, * pb; // //pint pa, pb; //pa int* //pb int* PINT pa, pb;//int * pa,pb; //pa -> int* //pb -> int return 0; } //Integer array - an array that holds integers //Character array - an array of characters // //Pointer array - an array of pointers
int main() { char* arr[] = { "abcdef", "qwer", "zhangsan" }; int i = 0; int sz = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < sz; i++) { printf("%s\n", arr[i]); } return 0; }
int main() { int arr1[] = { 1,2,3,4,5 }; int arr2[] = { 2,3,4,5,6 }; int arr3[] = { 3,4,5,6,7 }; int* arr[] = {arr1, arr2, arr3}; int i = 0; for (i = 0; i < 3; i++) { int j = 0; for (j = 0; j < 5; j++) { printf("%d ", arr[i][j]);//*(*(arr+i)+j) } printf("\n"); } return 0; }