在C语言中,我不确定如何更新指针的输出?

时间:2019-04-05 13:40:47

标签: c function loops pointers

我正在尝试跟踪代码以进行我即将进行的测试。我通常会打印步骤以查找值的更新方式,但是对于我当前的代码,我无法做到这一点。有人介意帮助我了解跟踪情况吗?

#include <stdio.h>
#include <stdlib.h>
void print(int *info, int size)
{
    int i,*data,*dataptr;
    for (i=0; i<size; i++)
        printf("info[%d]=%d\n",i,info[i]);
    printf("\n");
    return;
}
int main()
{
    int i,*data,*dataptr;
    data = (int *)malloc(4*sizeof(int));

    for (i=0; i<4; i++)
        data[i]=3*i;
            print(data,4); //output: 0 3 6 9 <-I understand this output

    *data = 5; //I get  
    dataptr = data;//
    dataptr++; //
    *dataptr = 1;// 
    print(data,4); //output: 5 1 6 9 

    *(data+2) = 4;
    *(dataptr+2)=2;

    print(data,4);//output: 5 1 4 2

    free(data);
return 0;
}

2 个答案:

答案 0 :(得分:2)

在下面,我注释了您的代码,解释了指针指向的位置。

#include <stdio.h>
#include <stdlib.h>
void print(int *info, int size)
{
    int i,*data,*dataptr;//what you want data, dataptr here? they are unused
    for (i=0; i<size; i++)
    printf("info[%d]=%d\n",i,info[i]);
    printf("\n");
    return;
}
int main()
{
    int i,*data,*dataptr;
    data = (int *)malloc(4*sizeof(int)); //From now on the data is an array of 4 element. Is equal with statement -> int data[4];

    for (i=0; i<4; i++)
    data[i]=3*i;
    print(data,4);

    *data = 5; //This line change the value of first element of array  
    dataptr = data;//point to first element of array(data[0])
    dataptr++; //increment the pointer by one, so point to the second element of array(data[1])
    *dataptr = 1;// change the value of second element of array(data[1])
    print(data,4); //output: 5 1 6 9 

    *(data+2) = 4;//change the value of third element of array. is equal data[2] = 4
    *(dataptr+2)=2;//dataptr point to second element, increament by 2, so now point to fourth element and change his value

    print(data,4);//output: 5 1 4 2

    free(data);
    return 0;
}

我不明白您实际上无法打印什么。如果您的意思是dataprt,那么您可以喜欢

printf("dataptr point to %d\n", *dataptr);

希望这有助于您执行代码。

答案 1 :(得分:0)

int main()
{
    int i,*data,*dataptr;
    data = (int *)malloc(4*sizeof(int));

    for (i=0; i<4; i++)
        data[i]=3*i;
    print(data,4); //output: 0 3 6 9 <-I understand this output

    *data = 5; // *data is the same as data[0] so you have 5 3 6 9  
    dataptr = data; // 
    dataptr++; // if you print dataptr you will have 3 6 9
    *dataptr = 1;// dataptr : 1 6 9
    print(data,4); //output: 5 1 6 9 ;

    *(data+2) = 4; // same as data[2] = 4 
    *(dataptr+2)=2; // same as dataptr[2] = 2

    print(data,4);//output: 5 1 4 2

    free(data);
return 0;
}

别忘了dataptr是data ++,因此它将指向* data的下一个值