c++ 코딩에 도움이 필요합니다.

익명 사용자의 이미지

c++ 공부 중인데 구조체를 이용하여서 번호와 이름 그리고 3과목의 점수를 입력 받아서 입력 받은 번호와 이름 3과목의 총합과 평균을 내는 코드를 만드는 중입니다. 소스는 다음과 같습니다.

#include <stdio.h>
#include <string.h>
#include <malloc.h>
 
struct exam{
	char* num;
	char* name;
	int score1;
	int score2;
	int score3;
};
 
int main() {
	struct exam test;
	while(strcmp(test.num,"end")!=0){
		printf("\nType a number<End=\"end\"> : ");
		scanf("%s",test.num);
		printf("\nType a name : ");
		scanf("%s",test.name);
		printf("\nType three scores : ");
		scanf("%d %d %d",&test.score1,&test.score2,&test.score3);
		int total=test.score1+test.score2+test.score3;
		int avg=(test.score1+test.score2+test.score3)/3;
		printf("\n%s     %s     %d %d %d %d %d",test.num,test.name,test.score1,test.score2,test.score3,total,avg);
		printf("\n================================================");
	}
}

실행을 해보면 Type a number<End="end"> : 까지는 나와서 번호를 입력하면 다음 문장이 실행 되지 않고 실행이 종료 됩니다.
그래서 혹시나 하여 while문 이전에 test.num=(char*)malloc(1); test.name=(char*)malloc(1);를 적어놓으니 실행이 잘 됐는데 왜 그런지 설명 좀 해주실 수 있나요?
익명 사용자의 이미지

무슨 교재로 C++를 공부하고 계신지는 잘 모르겠는데, 좀 오래된 책인 것 같군요.

C++에서 printf/scanf를? 문자열을 저장하기 위해 char*를?!

흠. C++를 배우기 전에 C를 꼭 배워야 하는지에 대해서도 논란의 여지가 있습니다만, C++의 탈을 쓴 C언어를 가르쳐도 되는지에 대해서는 또 다른 문제가 있군요.

요약하자면, 귀하의 코드는 C++ 코드가 아니라 C 코드입니다.

그리고 문제가 생긴 이유는, 귀하의 프로그램은 문자열을 입력받으려 하면서도 문자열을 위한 공간을 단 1바이트도 할당하지 않았기 때문이지요.

C언어에서 문자열을 다룰 때 초보자들이 헷갈려하는 부분이기도 합니다. 일반적으로 문자열을 저장하려면 문자 타입 변수(char 등)를 문자열 길이만큼 가지고 있어야 합니다.

가장 간단한 형태는 배열(char[] 등)이죠. 그리고 배열은 배열의 첫 원소를 가리키는 포인터(char * 등)로 무너지고요. 그래서 문자 포인터만 가지고 문자열을 가리킬 수 있습니다.

하지만 문자 포인터로 문자열을 나타낼 수 있다고 해서, 문자 포인터를 만들면 문자열이 생기는 건 아니지요. 집 주소를 알려주면 집에 찾아갈 수 있지만, 집 주소를 만든다고 집이 생기는 건 아니듯이요.

결국 scanf는 초기화되지 않은 문자 포인터를 받아 엉뚱한 곳에 문자열을 기록하려고 시도하다가 프로그램이 죽습니다.

malloc(1)을 호출해서 test.num을 초기화해주면, 문자열이 들어갈 위치를 단 한 칸이나마 확보하는 것입니다. 그러면 일단 잘 도는 것처럼 보이지만, 이는 C언어에서 또 다른 고질적인 문제인 buffer overflow를 초래합니다.

스포일러: C언어에서 문자열을 다루는 건 매우 성가십니다. 숙련된 사람은 실수 없이 할 수 있겠지만 정말 성가시지요. 대충 원리만 배우고, 라이브러리를 쓰세요. C++의 string이던가.

댓글 달기

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