배열(Array) 생성

2021. 10. 7. 22:51

핀토스하다가 정리.

 

1. 길이를 미리 정해주는 방법

char str[10];
struct file* fileTable[100];
struct Vector polygon[1000];

 

처음에 배열은 쓰레기 값으로 차있음.

 

단점) 길이가 고정되어있다. 사실상 못 늘림.

(새 길이의 배열 할당 후 데이터 옮기던가, 동적할당 활용)

 

 

2. 동적 할당

char *str = (char*)malloc(10); // char array
str[0] = 'a';

struct file** fileTable = (struct file**)calloc(1, 100); // struct file pointer array
fileTable[10] = sample_file;

struct Vector *polygon = (struct Vector*)calloc(1, 1000); // struct Vector array
polygon[999] = vec999;

TypeA의 배열 arr

TypeA * p = arr

(∵ The name of the array A is a constant pointer to the first element of the array)

 

arr[i] = *(arr+i) - arr을 p로 바꿔도 됨

https://stackoverflow.com/questions/48851598/are-arrays-in-c-a-syntactic-sugar-for-pointers

 

malloc, calloc

realloc

free

 

 

C++은 new, free 문법도 있음

(이렇게 배열 생성할 바엔 차라리 vector 쓰는게 낫긴 하겠다)

// https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers
int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

+ Recent posts