처음으로 c언어 공부하는데 배열의 원소를 서로 바꿔서 출력하고 싶은데 도와주세요.

77team의 이미지

#include<stdio.h>
#define size 5
void exchangeArray(int *a, int *b, int n);
void printArray(int a[], int n);
 
int main(void){
 
   int a[size] = {10,20,30,40,50};
   int b[size] = {50,40,30,20,10};
 
   printArray(a, size);
   printArray(b, size);
   exchangeArray(&a[size], &b[size], size);
   printArray(a, size);
   printArray(b, size);
 
   return 0;
}
 
void exchangeArray(int *a, int *b, int n){
 
   int temp;
 
   temp = *a;
   *a = *b;
   *b = temp;
}
 
void printArray(int a[], int n){
   int i;
   for(i = 0; i < n; i++){
      printf("%d \n",  a[i]);
   }
 
}

이렇게 썻는데 exchangeArray 함수가 작동을 안하는 것 같네요.. 뭐가 문제죠?

임종규의 이미지

작성하신 exchangeArray는 int형 변수 값 하나를 서로 교환하는 함수입니다.
즉, 원하는 배열의 모든 요소들을 교환하지는 않는다는 말입니다.

왜 그런가? 를 생각해보면..

배열의 이름(코드의 a와 b)은 일종의 상수 포인터입니다.
포인터가 일반 변수와 다르게 메모리 주소값을 가지는 변수라는 점에서는 같으나
가지고 있는 메모리 주소값을 변경할 수 없다라는 점에서 일반 포인터와 차이가 있습니다.

일반적인 포인터는 ...

int a = 0, b =1;
int *ptr = 0; // 포인터가 가지는 메모리 주소값은 0이라고 초기화.
 
ptr = &a;
printf("%d", *ptr); // a 값인 0이 출력
ptr = &b;
printf("%d", *ptr); // b 값인 1이 출력

위처럼 가지는 주소값을 변경이 가능합니다.

하지만 배열은 ...

int a[1] = {1};
int b[1] = {2};
 
a = b; // 에러 발생,

위처럼 단순한 할당으로는 변경이 불가능합니다.

일반적으로 어떠한 타입의 배열은 의미적으로 다음처럼 표현이 가능합니다.

Type ArrayName[Array-Size] 
Type * const ArrayName;

그렇다면..
어떻게 복사해야 할까요? 를 생각해보면...

배열의 이름을 통해서 각 배열의 요소들을 하나씩 교환해 주어야 합니다.

int a[3] = {0,1,2};
int b[3] = {11,12,13};
 
for (int i = 0; i < sizeof(a)/sizeof(int); ++i) {
    int tmp = a[i];
    a[i] = b[i];
    b[i] = tmp;
}

이러한 지식을 바탕으로 만들려고 했던 exchangeArrary를 바꿔주고,
당연히 함수 호출시에도 인자로 넘겨주는 것이 달라지겠죠?

코드는 직접 짜보시길...

/* How to Love Others */
while(GetDepth(Love) < Enough) DoLove();

shint의 이미지

...

굳이 데이터를 바꾸지 않더라도.
출력만 b, a로 바꿔도 되겠네요. ㅇ_ㅇ;;

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

ozon1000의 이미지

댓글이 너무 웃겨서요 ㅋㅋㅋㅋㅋㅋㅋㅋ

ozon1000의 이미지

exchangeArr함수에 인자를 가져가실때 질문자 께서는 &a[size], &b[size], size
이렇게 가져가셨는데요.

생각해보면 현재 size는 5입니다.
즉 a[5], b[5]의 각각 주소를 인자로 가져간다는 말이 되는데 이렇게 되면 실수를 하기 쉽습니다.(out of range)
저같은 경우에는
exchangeArray(a, b, size);
이런식으로 항상 가져갑니다. 왜냐하면 배열의 이름 자체는 그 변수의 주소 시작점이기 때문이죠.

void exchangeArray(int *a, int *b, int n)
{
int temp;
int i;
for(i = 0; i < n; i++)
{
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
함수의 원형은 이렇게 하시면 되겠네요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.