|
잘못 사용하고 있는듯 합니다.
1 char chtemp[]="Let me say those words as hently as I can";
2 chtemp = (char *)malloc(50); //이부분//
3 printf("%s \n",*chtemp);
4 free(chtemp);
1번에서 이미 문자열에 맞는 메모리를 컴파일러가 임의로 할당하고 이 주소를 chtemp 에 넘겨주고 있습니다.
2번에서 chtemp 에 새로이 메모리를 할당하고 이 주소를 넘겨주려고 했는데 이는 잘못된 경우 입니다.
배열의 이름은 주소를 나타내는 것은 맞으나 이는 const 입니다. 절대 변경 불가합니다.
따라서 2번 구문은 잘못됬습니다.
또 1번에서 말했듯이 chtemp 에 맞는 메모리가 있으므로 다시 할당할 필요가 없습니다.
3번 문자열을 화면에 뿌려 주기 위해서는 주소를 넘겨 주어야 합니다. *chtemp 가 아니라 chtemp를 넘겨주어야 합니다.
가령 문자열을 복사하고자 한다면
char *szCopy;
char chtemp[]="Let me say those words as hently as I can";
szCopy = (char *)malloc(sizeof(char) * 50); //이부분//
strcpy(szCopy,chtemp);
printf("%s \n",szCopy);
free(szCopy);
처럼 해야 합니다.
char *temp;
temp = "이렇게 사용하면 안됩니다.";
char *temp;
temp = (char *)malloc (sizeof(char) * 50);
strcpy(temp, "이렇게 사용해야 합니다");
free(temp);
춤추는대수사선 님이 쓰신 글 :
: 문제는
: char chtemp[]="Let me say those words as hently as I can"; 의 문자열을
: 동적 메모리에 보관하고 이를 출력하는 프로그램을 작성하여 보세요.
:
: ---------------제가 풀어볼려고했던 답--------------------
: #include <stdio.h>
: #include <stdlib.h>
:
: void main() {
:
: char chtemp[]="Let me say those words as hently as I can";
: chtemp = (char *)malloc(50); //이부분//
: printf("%s \n",*chtemp);
: free(chtemp);
: }
: -------------------------------------------------------------
:
: //이부분// 에서 에러가 나더군요!
: 에러메세지는(터보C++3.1 for Windows) Lvalue required 이고,
: 비주얼C++은
: error C2440: '=' : cannot convert from 'char *' to 'char [42]'
: There are no conversions to array types, although there are conversions to references or pointers to arrays
: Error executing cl.exe.
: 이렇게 나오네요
:
: 뭐가 문제일까요.......ㅡㅡa
:
: 김민식님 감사합니다.
|