当前位置:网站首页>c pointer learning (2)

c pointer learning (2)

2022-08-11 05:47:00 sunshine boy cony

cSmall problems encountered in pointer learning

(1)逗号运算符

int main() {
    
	int a[3][2] = {
     (0,1),(3,4),(5,6) };
	int* pt = a[0];
	printf("%d", pt[0]);
	//输出1
}

The main thing to note in this question is that(0,1),(3,4),(5,6),Parentheses are used so it means the comma operator,The last number stored in the array is {1,4,6}.p[0]=*(p+0)

(2)Pointers access strings directly

int main() {
    
        char str1[] = "hallo word";
        char str2[] = "hallo word";
        const char* str3 = "hallo word";
        const char* str4 = "hallo word";
        if (str1 == str2) {
    
                printf("same");
        }else{
    
                printf("not same");
        }printf("\n");
        if (str3 == str4) {
    
                printf("same");
        }
        else {
    
                printf("not same");
        }
        return 0;
        //输出
        //not same
        //same
}

前者输出not same毋庸置疑的,(将字符串放入数组中,str1与str2Both point to the address of the first element of an array.)
后者输出same,is because the string directly accessed by the pointer isconst的(Stored in a static area in memory),If it is modified, an error will be reported.

(3)

	int main() {
    
		int a[5][5] = {
     0 };
		int(*p)[4] = a;
		printf("%p,%d", &a[4][2]- &p[4][2],&a[4][2] - &p[4][2]);
		printf("%p,%d", &p[4][2]- &a[4][2],&p[4][2] - &a[4][2]);
	}
	//输出: 00000004 4
	// FFFFFFFC -4

首先明白int(*p)[4]是一个数组指针而不是指针数组,int(*p)[4] = a; p中存储的是a数组的首地址,对于pIn terms of its type is,The row storage capacity is 4,And the original array,The row storage capacity is 5.
其次明白p[4][2]的意义是*(*(p+4)+2),而&p[4][2]*(p+4)+2.
and understand%p%d的不同之处,For the former it will be in memory,should be stored16Complete output of the base number.The latter is output according to the process of integer output.
Knowing the above, you can do the calculation:a[5][2]指向的是a数组的第22位,而p[4][2]指向的是a数组的第18位.The difference between the two digits is 4,所以&a[4][2] - &p[4][2]对于4

原网站

版权声明
本文为[sunshine boy cony]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110512478670.html