Programing

C에서 * ptr + = 1과 * ptr ++의 차이점

lottogame 2020. 7. 12. 09:45
반응형

C에서 * ptr + = 1과 * ptr ++의 차이점


방금 C를 공부하기 시작했고 포인터를 함수의 매개 변수로 포인터에 전달하는 것에 대한 한 가지 예를 할 때 문제가 발견되었습니다.

이것은 내 샘플 코드입니다.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int* allocateIntArray(int* ptr, int size){
    if (ptr != NULL){
        for (int i = 0; i < size; i++){
            ptr[i] = i;
        }
    }
    return ptr;
}

void increasePointer(int** ptr){
    if (ptr != NULL){
        *ptr += 1; /* <----------------------------- This is line 16 */
    }
}

int main()
{
    int* p1 = (int*)malloc(sizeof(int)* 10);
    allocateIntArray(p1, 10);

    for (int i = 0; i < 10; i++){
        printf("%d\n", p1[i]);
    }

    increasePointer(&p1);
    printf("%d\n", *p1);
    p1--;
    free(p1);
    fgets(string, sizeof(string), stdin);
    return 0;
}

내가 수정하면 문제는 라인 (16)에서 발생 *ptr+=1*ptr++. 예상 결과는 전체 배열과 숫자 1이어야하지만 *ptr++결과를 사용할 때 0입니다.

+=1사이에 차이 ++있습니까? 둘 다 동일하다고 생각했습니다.


차이점은 운영자 우선 순위 때문입니다.

후행 증가 연산자 ++는 역 참조 연산자보다 우선 순위가 높습니다 *. 따라서 *ptr++와 같습니다 *(ptr++). 즉, 포스트 증분은 포인터가 가리키는 것이 아니라 포인터를 수정합니다.

대입 연산자 +=는 역 참조 연산자보다 우선 순위가 낮 *으므로 *ptr+=1동일합니다 (*ptr)+=1. 즉, 대입 연산자는 포인터가 가리키는 값을 수정하고 포인터 자체는 변경하지 않습니다.


귀하의 질문에 관련된 3 명의 운영자에 대한 우선 순위는 다음과 같습니다.

증분 후 ++> 역 참조 *> 할당+=

주제에 대한 자세한 내용은 페이지확인 하십시오 .

식을 구문 분석 할 때 일부 행에 나열된 연산자는 그 아래 행에 나열된 연산자보다 괄호로 묶인 것처럼 인수에 더 밀접하게 바인딩됩니다. 예를 들어, 식은 *p++로 해석되고로 해석 *(p++)되지 않습니다 (*p)++.

Long story short, in order to express this assignment *ptr+=1 using the post-increment operator you need to add parentheses to the dereference operator to give that operation precedence over ++ as in this (*ptr)++


Let's apply parentheses to show the order of operations

a + b / c
a + (b/c)

Let's do it again with

*ptr   += 1
(*ptr) += 1

And again with

*ptr++
*(ptr++)
  • In *ptr += 1, we increment the value of the variable our pointer points to.
  • In *ptr++, we increment the pointer after our entire statement (line of code) is done, and return a reference to the variable our pointer points to.

The latter allows you to do things like:

for(int i = 0; i < length; i++)
{
    // Copy value from *src and store it in *dest
    *dest++ = *src++;

    // Keep in mind that the above is equivalent to
    *(dest++) = *(src++);
}

This is a common method used to copy a src array into another dest array.


Very good question.

In K&R "C programming language" "5.1 Pointers and Addresses", we can get an answer for this.

"The unary operators * and & bind more tightly than arithmetic operators"

*ptr += 1      //Increment what ptr points to.

"Unary operators like * and ++ associate right to left."

*ptr++        //Increment prt instead of what ptr point to.

//It works like *(ptr++).

The correct way is:

(*ptr)++      //This will work.

*ptr += 1 : Increment data that ptr points to. *ptr++ : Increment pointer that is point to next memory location instead of the data that pointer points to.

참고URL : https://stackoverflow.com/questions/35306391/difference-between-ptr-1-and-ptr-in-c

반응형