嗨,有人可以告诉我以下代码做了什么

时间:2012-08-22 15:38:47

标签: c arrays pointers

大家好,有人请告诉我这行代码是做什么的

xdata.yarray[3] = *(ptr++);  
xdata.yarray[2] = *(ptr++);  
xdata.yarray[1] = *(ptr++);  
xdata.yarray[0] = *(ptr++);  

我试图找出其他人的代码,因此遇到问题 如果有人能提供一些有用的指针来解释别人的代码,也会感激不尽。

谢谢

如果代替 xdata 代替数据

,代码的含义会被更改

4 个答案:

答案 0 :(得分:3)

arr设置为ptr的初始值,代码会将值arr[0]arr[1]arr[2]arr[3]填入元素xdata.yarray[3],...,xdata.yarray[0] - 即它以相反的顺序复制四个元素的范围。作为副作用,它会修改ptr的值,使其最终为arr + 4

请注意*ptrptr[0]相同,而且表达式评估*(ptr++)相同,但ptr会增加。

答案 1 :(得分:2)

基本上是按ptr将数组指针复制到yarray的{​​{1}}成员,只是按相反的顺序。

答案 2 :(得分:1)

它分配数据并递增指针,以便下一个赋值可以使用ptr指向的下一个值。

它只相当于:

xdata.yarray[3] = *ptr;  
ptr++;
xdata.yarray[2] = *ptr;  
ptr++;
xdata.yarray[1] = *ptr;  
ptr++;
xdata.yarray[0] = *ptr;  
ptr++;

答案 3 :(得分:1)

关于此代码的作用,您有很多答案。据推测,应对ptr指向的某些数组的内容,并将其以相反的顺序存储到struct“xdata”中包含的另一个数组中。

你问过如何自己解读这个问题,这是一个很好的问题,最好的学习方法就是亲自去做。这是我的建议:拿走你所知道的,根据它创建你自己的小程序,并查看输出。

例如,在没有看到所有代码的情况下,我知道你有一个包含4个元素的数组“yarray”,并且你将来自解引用指针的值存储到它中。您可以制作一个类似下面的程序来查看代码的反应:

void main()
{
    int yarray[4] = {0, 0, 0, 0};
    int my_array[4] = {1, 2, 3, 4};
    int *ptr = my_array;
    int cntr;

    for(cntr = 0; cntr < 4; cntr++)
        printf("then: my_array = %d, and yarray = %d\n", my_array[cntr], yarray[cntr]);

    //Add the code that you're not sure what it does here...
    yarray[3] = *(ptr++);
    yarray[2] = *(ptr++);
    yarray[1] = *(ptr++);
    yarray[0] = *(ptr++);

    //Check out the results!
    for(cntr = 0; cntr < 4; cntr++)
        printf("now: my_array = %d, and yarray = %d\n", my_array[cntr], yarray[cntr]);
}

现在您可以看到代码正在颠倒ptr指向的内容的顺序并将其存储在yarray中。

then: my_array= 1, and yarray = 0
then: my_array= 2, and yarray = 0
then: my_array= 3, and yarray = 0
then: my_array= 4, and yarray = 0

now:  my_array= 1, and yarray = 4
now:  my_array= 2, and yarray = 3
now:  my_array= 3, and yarray = 2
now:  my_array= 4, and yarray = 1