programing

포인터 주소와 포인터 값을 증가시키는 방법

yoursource 2022. 8. 27. 14:05
반응형

포인터 주소와 포인터 값을 증가시키는 방법

가정해 봅시다.

int *p;
int a = 100;
p = &a;

다음 코드는 실제로 무엇을 어떻게 합니까?

p++;
++p;
++*p;
++(*p);
++*(p);
*p++;
(*p)++;
*(p)++;
*++p;
*(++p);

코딩에 관해서는 좀 복잡하지만 이렇게 코딩하면 실제로 어떤 일이 일어날지 알고 싶습니다.

「」의 과 같이 되어 있다고 합니다.a=5120300, 포인터에 저장되어 p는 "" 입니다.3560200 그럼 자, 제, 떤의 값은 어떻게 요?p & a각각진 행행 ???

먼저 ++ 연산자가 * 연산자보다 우선하고 () 연산자가 다른 모든 연산자보다 우선합니다.

둘째, ++번호 연산자는 number++ 연산자와 동일합니다.차이점은 number++는 숫자를 반환한 후 숫자를 증가시키고 ++number는 먼저 증가시킨 후 반환한다는 것입니다.

셋째, 포인터의 값을 증가시키면 포인터의 콘텐츠 크기만큼 증가합니다.즉, 어레이 내에서 반복하는 것처럼 증가합니다.

정리하면 다음과 같습니다.

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value pointed at by ptr is incremented
++(*ptr); // The value pointed at by ptr is incremented
++*(ptr); // The value pointed at by ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value pointed at by ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault

여러 가지 경우가 있기 때문에 제가 실수를 했을지도 모르니, 틀렸다면 정정해 주세요.

편집:

제가 틀렸습니다.우선 순위는 제가 쓴 것보다 조금 복잡합니다.여기서 보세요.http://en.cppreference.com/w/cpp/language/operator_precedence

프로그램을 확인했는데 결과는 다음과 같습니다.

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

다음은 다양한 "그냥 인쇄" 제안의 인스턴스화입니다.나는 그것이 유익하다는 것을 알았다.

#include "stdio.h"

int main() {
    static int x = 5;
    static int *p = &x;
    printf("(int) p   => %d\n",(int) p);
    printf("(int) p++ => %d\n",(int) p++);
    x = 5; p = &x;
    printf("(int) ++p => %d\n",(int) ++p);
    x = 5; p = &x;
    printf("++*p      => %d\n",++*p);
    x = 5; p = &x;
    printf("++(*p)    => %d\n",++(*p));
    x = 5; p = &x;
    printf("++*(p)    => %d\n",++*(p));
    x = 5; p = &x;
    printf("*p++      => %d\n",*p++);
    x = 5; p = &x;
    printf("(*p)++    => %d\n",(*p)++);
    x = 5; p = &x;
    printf("*(p)++    => %d\n",*(p)++);
    x = 5; p = &x;
    printf("*++p      => %d\n",*++p);
    x = 5; p = &x;
    printf("*(++p)    => %d\n",*(++p));
    return 0;
}

다시 돌아오다

(int) p   => 256688152
(int) p++ => 256688152
(int) ++p => 256688156
++*p      => 6
++(*p)    => 6
++*(p)    => 6
*p++      => 5
(*p)++    => 5
*(p)++    => 5
*++p      => 0
*(++p)    => 0

를 인포 to to to to to to i to i i i to i i i to 。int스스무리무리무리무리무리무리무리무리무리무리무리무리무리.

저는 GCC로 컴파일했습니다.

        Note:
        1) Both ++ and * have same precedence(priority), so the associativity comes into picture.
        2) in this case Associativity is from **Right-Left**

        important table to remember in case of pointers and arrays: 

        operators           precedence        associativity

    1)  () , []                1               left-right
    2)  *  , identifier        2               right-left
    3)  <data type>            3               ----------

        let me give an example, this might help;

        char **str;
        str = (char **)malloc(sizeof(char*)*2); // allocate mem for 2 char*
        str[0]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char
        str[1]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char

        strcpy(str[0],"abcd");  // assigning value
        strcpy(str[1],"efgh");  // assigning value

        while(*str)
        {
            cout<<*str<<endl;   // printing the string
            *str++;             // incrementing the address(pointer)
                                // check above about the prcedence and associativity
        }
        free(str[0]);
        free(str[1]);
        free(str);

포인터 주소 포인터 값의 증가 방법에 대해그런 것 같아요++(*p++);는 실제로 적절하게 정의되어 있으며, 다음과 같은 작업을 수행할 수 있습니다.

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

시퀀스 포인트 전에 같은 것을 두 번 수정하는 것이 아닙니다.대부분의 경우 좋은 스타일은 아닌 것 같아요. 제 취향에는 좀 신비롭습니다.

언급URL : https://stackoverflow.com/questions/8208021/how-to-increment-a-pointer-address-and-pointers-value

반응형