I am trying to trace a code to practice for my upcoming test. I usually print the steps to find how the values are getting updated but for my current code, I can't do that. Would anyone mind helping me understand the tracing??

#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 Answers

2
aragon On Best Solutions

Below i comment your code explaining where the pointers point to.

#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;
}

I don't understand what actually you can't print. if you mean dataprt you can like

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

Hope this help you about the execution of the code.

0
Hamza Ince On
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;
}

don't forget that dataptr is data++ so it will point to the next value of *data