sourcetip

C에서 참조로 구조 전달

fileupload 2023. 7. 22. 10:21
반응형

C에서 참조로 구조 전달

이 코드가 맞습니까?예상대로 실행되지만, 이 코드가 구조체에 대한 포인터와 점 표기법을 올바르게 사용하고 있습니까?

struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}

포인터와 점 표기법을 사용하는 것이 좋습니다.컴파일러는 문제가 있는 경우 오류 및/또는 경고를 제공해야 합니다.

다음은 구조체, 포인터, 함수 및 변수 범위의 사용에 대한 추가적인 참고 사항과 함께 코드의 복사본입니다.

참고: 아래 소스 예제의 코드 쓰기 차이는 함수 정의/선언에서 다음과 같이 구조 이름 뒤와 별표 앞에 공백을 넣었다는 것입니다.struct someStruct *p1;그리고 OP는 별표 뒤에 공백을 두었습니다.struct someStruct* p1;컴파일러에는 차이가 없고 프로그래머에게는 가독성과 습관의 차이가 있을 뿐입니다.변수 이름 옆에 별표를 붙여 별표가 변수 이름 옆에 있는지 확인하고 싶습니다.선언 또는 정의에 변수가 둘 이상 있는 경우 특히 중요합니다.쓰기struct someStruct *p1, *p2, var1;두 개의 포인터를 만들 것입니다.p1그리고.p2변수도 있고,var1.쓰기struct someStruct* p1, p2, var1;단일 포인터를 만듭니다.p1그리고 두 변수p2그리고.var1

// Define the new variable type which is a struct.
// This definition must be visible to any function that is accessing the
// members of a variable of this type.
struct someStruct {
    unsigned int total;
};

/*
 * Modifies the struct that exists in the calling function.
 *   Function test() takes a pointer to a struct someStruct variable
 *   so that any modifications to the variable made in the function test()
 *   will be to the variable pointed to.
 *   A pointer contains the address of a variable and is not the variable iteself.
 *   This allows the function test() to modify the variable provided by the
 *   caller of test() rather than a local copy.
 */
int test(struct someStruct *state) {
    state->total = 4;
    return 0;
}

/* 
 * Modifies the local copy of the struct, the original
 * in the calling function is not modified.
 * The C compiler will make a copy of the variable provided by the
 * caller of function test2() and so any changes that test2() makes
 * to the argument will be discarded since test2() is working with a
 * copy of the caller's variable and not the actual variable.
 */
int test2(struct someStruct state) {
    state.total = 8;
    return 0;
}

/*
 * Make a local copy of the argument then modify the local copy.
 * Until the assignment of the local copy to the argument is made,
 * the changes to the local copy are not made to the argument.
 * To make any changes made to the local copy in the argument,
 * you need to assign the local copy to the argument.
 */
int test3(struct someStruct *state) {
    struct someStruct  stateCopy;
    stateCopy = *state;    // make a local copy of the struct
    stateCopy.total = 12;  // modify the local copy of the struct
    *state = stateCopy;    /* assign the local copy back to the original in the
                              calling function. Assigning by dereferencing pointer. */
    return 0;
}

int main () {
    struct someStruct s;

    /* Set the value then call a function that will change the value. */
    s.total = 5;
    test(&s);
    printf("after test(): s.total = %d\n", s.total);

    /*
     * Set the value then call a function that will change its local copy 
     * but not this one.
     */
    s.total = 5;
    test2(s);
    printf("after test2(): s.total = %d\n", s.total);

    /* 
     * Call a function that will make a copy, change the copy,
       then put the copy into this one.
     */
    test3(&s);
    printf("after test3(): s.total = %d\n", s.total);

    return 0;
}

구조물의 올바른 사용법입니다.반환 값에 대한 질문이 있습니다.

또한 서명되지 않은 int를 인쇄하는 중이므로 다음을 사용해야 합니다.%u대신에%d.

네, 맞습니다.그것은 구조를 만듭니다.s는 총계를 5로 설정하고 포인터를 함수에 전달하여 포인터를 사용하여 총계를 4로 설정한 다음 출력합니다.->는 구조체에 대한 포인터의 멤버들을 위한 것입니다..구조체 멤버용입니다.당신이 그것들을 사용한 것처럼.

하지만 반환 값은 다릅니다.test아마 무효가 되어야 할 것이고, 그리고.main가 필요합니다.return 0맨 끝에

네. 맞습니다.만약 그것이 (. / ->의 관점에서) 아니라면, 당신의 컴파일러는 소리를 질렀을 것입니다.

네, 구조물의 올바른 사용법입니다.사용할 수도 있습니다.

typedef struct someStruct {
 unsigned int total;
} someStruct;

그러면 당신은 쓸 필요가 없을 것입니다.struct someStruct s;몇 번이고 반복하지만 사용할 수 있습니다.someStruct s;그리고나서.

언급URL : https://stackoverflow.com/questions/4316314/pass-struct-by-reference-in-c

반응형