코딩/C++

[C++ 기초] 동적 구조체(struct) / 문자열 메모리 할당

영넌 2020. 10. 23. 16:18
  • C언어 

  struct 키워드를 구조체 이름 앞에 꼭 붙여야함

  동적으로 구조체 공간 생성을 위해서는 malloc 사용, free로 해제

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

struct things {
	char name[20];
	double weight;
	double price;
};

int main()
{
	using namespace std;

	struct things* pt = (struct things*)malloc(sizeof(struct things));


	return 0;
}

 

  • C++

  struct 키워드 없이 구조체 이름 만으로도 사용 가능

  동적 구조체는 array와 똑같이 new와 delete 사용

#include <iostream>

struct things {
	char name[20];
	double weight;
	double price;
};

int main()
{
	using namespace std;

	things* pt = new things;

	cout << "Enter name: ";
	cin.get(pt->name,20);	

	cout << "Enter weight: ";
	cin >> pt->weight;

	cout << "Enter price:";
	cin >> (*pt).price;

	return 0;
}

 

 

* 문자열 길이 맞춤형 메모리 할당

 문자열의 길이가 다를 경우, 일률적인 버퍼를 사용하면 메모리 낭비

 ex) 문자열 길이가 대부분 10, 1개만 100일 경우

 

  최대 길이로 문자열 입력을 받고,

  실제 길이에 따라 메모리를 할당받아 저장

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>

//strlen.h <---> cstring
using namespace std;

char* getname() {
	char temp[101];

	cout << "Enter name:";
	cin >> temp;

	char* pn = new char[strlen(temp) + 1]; //NULL까지

	strcpy(pn, temp);

	return pn; //주소 반환
	
}

int main()
{
	char* name;
	name = getname();

	cout << "Name: " << name << endl;
	cout << "Name address: " << (int*)name << endl;

	delete[] name;

	return 0;
}