산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C 구조체와 포인터

C 구조체 및 포인터

이 튜토리얼에서는 포인터를 사용하여 C 프로그래밍에서 구조체의 멤버에 액세스하는 방법을 배웁니다. 또한 구조체 유형의 메모리를 동적으로 할당하는 방법을 배우게 됩니다.

구조체에서 포인터를 사용하는 방법을 배우기 전에 다음 자습서를 확인하세요.

<시간>

구조체에 대한 C 포인터

구조체에 대한 포인터를 만드는 방법은 다음과 같습니다.

struct name {
    member1;
    member2;
    .
    .
};

int main()
{
    struct name *ptr, Harry;
}

여기, ptr struct에 대한 포인터입니다. .

<시간>

예:포인터를 사용하여 구성원 액세스

포인터를 사용하여 구조의 멤버에 액세스하려면 ->을 사용합니다. 연산자.

#include <stdio.h>
struct person
{
   int age;
   float weight;
};

int main()
{
    struct person *personPtr, person1;
    personPtr = &person1;   

    printf("Enter age: ");
    scanf("%d", &personPtr->age);

    printf("Enter weight: ");
    scanf("%f", &personPtr->weight);

    printf("Displaying:\n");
    printf("Age: %d\n", personPtr->age);
    printf("weight: %f", personPtr->weight);

    return 0;
}

이 예에서 person1의 주소는 personPtr에 저장됩니다. personPtr = &person1;을 사용하는 포인터 .

이제 person1의 구성원에 액세스할 수 있습니다. personPtr 사용 포인터.

그건 그렇고,

<시간>

구조체의 동적 메모리 할당

이 섹션을 진행하기 전에 C 동적 메모리 할당을 확인하는 것이 좋습니다.

때로는 선언한 구조체 변수의 수가 충분하지 않을 수 있습니다. 런타임 중에 메모리를 할당해야 할 수도 있습니다. 다음은 C 프로그래밍에서 이를 달성하는 방법입니다.

예:구조체의 동적 메모리 할당

#include <stdio.h>
#include <stdlib.h>
struct person {
   int age;
   float weight;
   char name[30];
};

int main()
{
   struct person *ptr;
   int i, n;

   printf("Enter the number of persons: ");
   scanf("%d", &n);

   // allocating memory for n numbers of struct person
   ptr = (struct person*) malloc(n * sizeof(struct person));

   for(i = 0; i < n; ++i)
   {
       printf("Enter first name and age respectively: ");

       // To access members of 1st struct person,
       // ptr->name and ptr->age is used

       // To access members of 2nd struct person,
       // (ptr+1)->name and (ptr+1)->age is used
       scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
   }

   printf("Displaying Information:\n");
   for(i = 0; i < n; ++i)
       printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);

   return 0;
}

프로그램을 실행하면 다음과 같이 출력됩니다.

Enter the number of persons:  2
Enter first name and age respectively:  Harry 24
Enter first name and age respectively:  Gary 32
Displaying Information:
Name: Harry	Age: 24
Name: Gary	Age: 32

위의 예에서 n n에서 생성되는 구조체 변수의 수 사용자가 입력합니다.

n에 대한 메모리를 할당하려면 구조체 사람의 수 , 우리가 사용,

ptr = (struct person*) malloc(n * sizeof(struct person));

그런 다음 ptr을 사용했습니다. person의 요소에 액세스하기 위한 포인터 .


C 언어

  1. C# 키워드 및 식별자
  2. C# 클래스 및 개체
  3. C# 추상 클래스 및 메서드
  4. C# 부분 클래스 및 부분 메서드
  5. C# 봉인된 클래스 및 메서드
  6. C# 구조체
  7. C 키워드 및 식별자
  8. C 포인터
  9. 배열과 포인터의 관계
  10. C 패스 주소 및 포인터