C언어 코드에 문제점이뭔지 궁금합니다.

NaziCube의 이미지

C언어 책보며 문제가 나와서 하는도중에 나온 오류같은건데 일단 맨처음짠게

#include <stdio.h>
 
int main(){
   int df,arr[df],ct=0;
   printf("몇개의 정수를 입력 할 것인가 : ");
   scanf("%d", &df);
   printf("정렬할 숫자 "); 
   for(;ct<df;ct++){
      printf("입력 : ");
      scanf("%d", &arr[ct]);
   }
   return 0;
}

이거입니다. 여기서 문제점이 df에다가 12를 입력하면 arr[ct]에 12개의 정수를 입력이 가능할 줄 알았는데 막상해보니 6개만 입력이 가능해서

#include <stdio.h>
 
int sort(int * ptr);
 
int main(){
	int df;
	printf("몇개의 정수를 입력 할 것인가 : ");
	scanf("%d", &df);
	sort(&df);
	return 0;
}
 
int sort(int * ptr){
	int arr[*ptr], ct=0;
	for(;ct<*ptr;ct++) scanf("%d", &arr[*ptr]);
}

이렇게 바꾸어봤는데 여기서는 정상작동을 합니다.
비슷하게 코드를 만든거같은데 뭐가 문제일까요?

shint의 이미지


아래 코드는 잘 됩니다.

#include <iostream>
 
 
 
int sort(int *ptr)
{
	printf("sort()  %d\n", *ptr);
	int arr[*ptr];
	int ct=0;
	for(;ct<*ptr;ct++)
	{
		printf("입력할 숫자 : ");
		scanf("%d", &arr[*ptr]);
		printf("&arr[*ptr]  %d\n", arr[*ptr]);
	}
}
 
 
int main(int argc, char** argv)
{
	int df;
	int ct=0;
	printf("몇개의 정수를 입력 할 것인가 : ");
	scanf("%d", &df);
 
	printf("정렬할 숫자 "); 
	sort(&df);
 
	return 0;
}

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

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

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

bushi의 이미지

다음 둘 중의 하나로 오동작 할 것 같습니다.
1. sort() 함수의 ct 변수가 오염되거나
2. sort() 함수에서 다른 함수를 호출했다 복귀한다음 arr[*ptr] 을 다시 읽을 때 괴상한 값이 읽히거나.

익명 사용자의 이미지

int df,arr[df],ct=0;
요게 말이 안되는듯 한데요... 잘~ 생각해보시길...

김정균의 이미지

아마 컴파일러에 따라 다른 결과가 나올 수도 있을 것 같습니다.

일단, df가 결정이 되게 전에 arr이 compiler에서 초기화 되기 때문에 원하시는 결과가 안나올 것 같네요. 원하시는 결과를 바라신다면 다음과 같이 만들면 되지 않을까 싶습니다. 물론 이 코드는 컴파일러에 따라 다른 결과를 보일지 모르겠지만 gcc 3 이상에서는 동작할 겁니다. (gcc 2에서는 declare 에러가 발생할 겁니다. gcc2는 코드 중간에서 변수 선언이 안되거든요.)

#include <stdio.h>
 
int main(){
   int df,ct=0;
   printf("몇개의 정수를 입력 할 것인가 : ");
   scanf("%d", &df);
 
   printf("정렬할 숫자\n");
   int arr[df];
   for(;ct<df;ct++){
      printf("입력 : ");
      scanf("%d", &arr[ct]);
   }
   return 0;
}

P.S
코드는 code tag block으로 감싸 주시면 제대로 보여줄 수 있습니다. 일단 본문은 제가 수정해 드렸습니다.

quodvide의 이미지

맨처음에 int df,arr[df] 이게 가능한가요?
df를 초기화 하지도 않았고 쓰레기값 들어있을텐데 그 값으로 arr[df]를 선언해버리면..
int df, *arr, cf = 0으로 선언 해놓고 df 받고난후 메모리할당하시는게 나을듯 싶어요

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.