Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active March 4, 2021 07:51
Show Gist options
  • Select an option

  • Save nattybear/d11e627bd7a80897ec59737b102cb5ff to your computer and use it in GitHub Desktop.

Select an option

Save nattybear/d11e627bd7a80897ec59737b102cb5ff to your computer and use it in GitHub Desktop.
C언어 함수의 인자로 배열을 넣을 때

C언어 함수의 인자로 배열을 넣을 때

아래 함수 change_array를 정의할 때 인자에 적은 배열의 크기 20은 무시됩니다.

void change_array(int a[20])

그래서 그냥 아래와 같아집니다.

void change_array(int a[])

따라서 말씀하신 것처럼 아래와 같이 동작하는 것은 아닙니다.

int a[20] = atr;

이 때에는 아래처럼 배열의 주소를 인자로 넘겨준 것이 맞습니다.

a = atr;

배열을 초기화 할 때는 = 표시 오른쪽에 비어 있는 배열이나 배열의 내용만 적을 수 있습니다.

아래와 같이 배열의 내용을 적어야 할 곳에 배열의 주소 를 적으면 컴파일 시 에러가 발생합니다.

int arr[5] = atr;  // error

전체 코드를 아래 다시 적어 봅니다.

#include <stdio.h>

void change_array(int xs[])
{
  xs[4] = 100;
}

int main()
{
  int xs[5] = {1, 2, 3, 4, 5};
  change_array(xs);
  printf("%d\n", xs[4]);  // 100
  return 0;
}

감사합니다.

참고

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment