문제

My code is:

 main()
{
  static int arr[]={97,98,99,100,101,102,103,104};
  int *ptr=arr+1;
  print(++ptr,ptr--,ptr,ptr++,++ptr);
}
print(int*a,int*b,int*c,int*d,int*e)
{
    printf("%d %d %d %d %d",*a,*b,*c,*d,*e);

}

The output is: 100 100 100 99 100

I'm unable to understand this question.

Please somebody explain me this code and it's output.

Thanks.

도움이 되었습니까?

해결책

First, this line contains undefined behavior

print(++ptr,ptr--,ptr,ptr++,++ptr);

because it uses a variable that is part of an expression with side effect multiple times without reaching a sequence point.

In the code static keyword is used so i thought that each time it would take a different input.

Presence or absence of static keyword makes no difference in this example, because the code never prints the value of the pointer, only the content of memory pointed to by that pointer.

You can remove undefined behavior by moving each expression with side effects to a separate line, like this:

static int arr[]={97,98,99,100,101,102,103,104}; // static can be removed
int *ptr=arr+1;         // Start at index 1
printf("%d\n", *++ptr); // Move to index 2, prints 99 
printf("%d\n", *ptr--); // Print 99, move to index 1
printf("%d\n", *ptr);   // Print 98, stay at position 1
printf("%d\n", *ptr++); // Print 98, move to position 2
printf("%d\n", *++ptr); // Move to position 3, print 100

(demo)

Now the output is different (and correct):

99
99
98
98
100

This is the output that you should expect to have based on the semantic of the pre-increment/decrement and post-increment/decrement operators.

다른 팁

That static keyword has no effect here as main will only be called once.

++ptr means increment the pointer and then pass it (the incremented pointer) to the function.
ptr++ means increment the pointer after it's passed to the function.

I compiled the code and ran it and got a different result:

99 99 98 98 100

'static' doesn't really do anything in your code. You can use it to keep the value of a variable in a function between calls. If this is what you want to know about then maybe you need to change the question slightly.

As for why it gives these numbers: Your code int *ptr=arr+1 means 'create a pointer to an int and initialise it to point at one more than where 'arr' starts. one more in this case is one int more, so this is usually 4 bytes further along in the memory. So ptr is pointing at arr[1], which is 98. Then you increment it in the call to print() ++ptr, so you're moving along one more, to 99, before you print it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top