programing

구조물을 기능으로 전달

bestcode 2022. 8. 15. 21:15
반응형

구조물을 기능으로 전달

저는 새로운 C프로그래머인데 어떻게 합격할 수 있는지 알고 싶었어요.struct함수에 도달합니다.오류가 발생하여 올바른 구문을 찾을 수 없습니다.여기 그 코드가 있습니다.

구조:

struct student{
    char firstname[30];
    char surname[30];
};

struct student person;

문의:

addStudent(person);

프로토타입:

void addStudent(struct student);

실제 기능:

void addStudent(person)
{
    return;
}

컴파일러 오류:

행 21: 경고: 의심스러운 태그 선언: 구조 학생
223행: 인수 #1은 프로토타입과 호환되지 않습니다.

이 방법으로 패스할 수 있습니다.struct참고 자료로즉, 기능에서 액세스 할 수 있는 것은,struct함수를 벗어나 값을 수정합니다.이를 수행하려면 구조물에 대한 포인터를 함수에 전달해야 합니다.

#include <stdio.h>
/* card structure definition */
struct card
{
    int face; // define pointer face
}; // end structure card

typedef struct card Card ;

/* prototype */
void passByReference(Card *c) ;

int main(void)
{
    Card c ;
    c.face = 1 ;
    Card *cptr = &c ; // pointer to Card c

    printf("The value of c before function passing = %d\n", c.face);
    printf("The value of cptr before function = %d\n",cptr->face);

    passByReference(cptr);

    printf("The value of c after function passing = %d\n", c.face);

    return 0 ; // successfully ran program
}

void passByReference(Card *c)
{
    c->face = 4;
}

이렇게 통과하면struct값별로 표시되므로 함수는 의 복사본을 수신합니다.struct외부 구조에 액세스하여 수정할 수 없습니다.'외관'이란 '외관'을 말합니다.

#include <stdio.h>


/* global card structure definition */
struct card
{
    int face ; // define pointer face
};// end structure card

typedef struct card Card ;

/* function prototypes */
void passByValue(Card c);

int main(void)
{
    Card c ;
    c.face = 1;

    printf("c.face before passByValue() = %d\n", c.face);

    passByValue(c);

    printf("c.face after passByValue() = %d\n",c.face);
    printf("As you can see the value of c did not change\n");
    printf("\nand the Card c inside the function has been destroyed"
        "\n(no longer in memory)");
}


void passByValue(Card c)
{
    c.face = 5;
}

회선 기능의 실장은 다음과 같습니다.

void addStudent(struct student person) {

}

person는 유형이 아니라 변수이므로 함수 파라미터의 유형으로 사용할 수 없습니다.

또한 함수의 프로토타입 전에 구조가 정의되었는지 확인하십시오.addStudent시제품이 사용하는 대로요.

구조물을 다른 기능에 전달할 때는 일반적으로 위에서 Donnell이 제안한 대로 하고 대신 참조로 전달하는 것이 더 나을 것이다.

이를 위한 매우 좋은 이유는 변경 내용을 적용하려는 경우 변경 내용을 인스턴스를 만든 함수로 되돌아가기 쉽기 때문입니다.

다음으로 가장 간단한 방법의 예를 제시하겠습니다.

#include <stdio.h>

typedef struct student {
    int age;
} student;

void addStudent(student *s) {
    /* Here we can use the arrow operator (->) to dereference 
       the pointer and access any of it's members: */
    s->age = 10;
}

int main(void) {

    student aStudent = {0};     /* create an instance of the student struct */
    addStudent(&aStudent);      /* pass a pointer to the instance */

    printf("%d", aStudent.age);

    return 0;
}

이 예에서는 의 인수가addStudent()함수는 의 인스턴스에 대한 포인터입니다.student구조 -student *smain()의 인스턴스를 만듭니다.student구조화 후 참조를 전달한다.addStudent()기준 연산자를 사용하여 함수(&).

에서addStudent()화살표 연산자를 사용할 수 있습니다(->포인터의 참조를 해제하고 포인터의 멤버에 액세스 합니다(기능적으로는 다음과 같습니다).(*s).age).

에서 변경한 경우addStudent()로 돌아가면 함수가 반영됩니다.main()포인터가 메모리 내의 어느 위치에 대한 참조를 제공했기 때문입니다.student구조가 저장되고 있습니다.이는 에 의해 설명됩니다.printf()이 예에서는 "10"이 출력됩니다.

참조를 전달하지 않으면 실제로 함수에 전달한 구조의 복사본을 사용하여 작업하게 됩니다. 즉, 로 돌아갈 때 변경 사항이 반영되지 않습니다.main하지 않는 한! - 새로운 버전의 구조를 으로 되돌리는 을 구현하지 않는 한! - '메인' 또는 ''으로 되돌리는 방법

비록 포인터가 처음에는 불쾌하게 느껴질지라도, 일단 여러분이 그것들이 어떻게 작동하는지, 그리고 왜 그것들이 매우 편리한지를 알게 되면, 제2의 천성이 되고, 여러분은 그것 없이 어떻게 대처했는지 궁금해 할 것입니다!

직접 유형을 지정해야 합니다.

void addStudent(struct student person) {
...
}

또한 구조를 사용할 때마다 structure를 입력할 필요가 없도록 구조를 다음과 같이 입력할 수 있습니다.

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

대신:

void addStudent(person)
{
    return;
}

이것을 시험해 보세요.

void addStudent(student person)
{
    return;
}

이미 'student'라는 구조를 선언했으므로 다음과 같이 함수 구현에서 반드시 지정할 필요는 없습니다.

void addStudent(struct student person)
{
    return;
}

언급URL : https://stackoverflow.com/questions/10370047/passing-struct-to-function

반응형