C언어 관련 문제에 대한 답이 맞는지 확인 받고 싶습니다

whdtjr222의 이미지

문제1.

#include <stdio.h>
int main()
{
	char s1[50], s2[50] = "Hello";
	s1 = s2;
	return 0;
}

답1. 런타임 에러, 컴파일 에러, Hello 출력, 결과값 없음 중
틀린 부분은 s1 = s2 이고 또 해당 코드는 컴파일 에러라고 생각했습니다. s2는 배열의 시작주소이고 s1은 l-value로 수정이 불가능(?) 하다고 알고 있기 때문입니다..

문제2.

#include <stdio.h>
int main()
{
	int arr[] = { 10, 20, 30, 40, 50, 60 };
	int* ptr1 = arr;
	int* ptr2 = arr + 5;
	printf("Number of elements between two pointers are : %d\n",
		(ptr2- ptr1));
 
	printf("Number of elements between two pointers are : %d\n",
		((char*)ptr2 - (char*)ptr1));
 
	return 0;
}

답2. 해당 코드를 실행한 결과 답은 5와 20입니다
첫번째 5는 ptr2 의 주소가 (arr[0] 주소 + sizeof(int)*5) 이므로 ptr2 - ptr1 시에
20/sizeof(int)로 5가 나오는게 맞다고 생각했고
두번째 20은 char* 로 형변환이 되었기 때문에 마지막 20/sizeof(char)로 20이 나오는게 맞다고 생각했습니다

문제3.

#include <stdio.h>
int main()
{
	void* pVoid;
	pVoid = (void*)0;
	printf("%lu",sizeof(pVoid));
	return 0;
}

답3.
(A) Assigning (void *)0 to pVoid isn’t correct because memory hasn’t been allocated. That’s why
no compile error, but it'll result in runtime error.
(B) Assigning (void *)0 to pVoid isn’t correct because a hard coded value (here zero i.e. 0) can’t be
assigned to any pointer. That’s why it'll result in a compile error.
(C) No compile issue and no run time issue. And the size of the void pointer i.e. pVoid would equal to
the size of int.
(D) sizeof() operator isn’t defined for a pointer of void type

중 고르는 것인데 해당 문제는 뭘 묻는 것인지 모르겠어서 검색해보니.. 널 포인터에 관한 문제인 듯한데 여전히 잘 모르겠습니다.. 저에게 깨달음을 주셨으면 좋겠습니다..

라스코니의 이미지

문3)
void* pVoid;
pVoid = (void*)0;

void* pVoid = NULL;

과 같고, sizeof()도 문제없어 보이는데요.

whdtjr222의 이미지

null과 같은 의미이군요

익명 사용자의 이미지

3번에 답이 없는거같은데요 ㄷㄷ...
내가 C언어를 헛배웠나...

(A) pVoide에 정의와 동시에 초기값을 주지 않은 것이 좋은 practice라고 할 수는 없지만, 주어진 상황에서 런타임 에러를 일으킨다고 볼 수는 없습니다.

(B) (void*)0는 아주 정석적인 null pointer constant입니다. 어떤 포인터 타입에도 대입할 수 있죠.

(C) 컴파일 및 런타임 이슈가 없다고 하기엔...

printf("%lu",sizeof(pVoid)); 부분이 걸리는군요.
sizeof의 결과 타입은 size_t입니다.
이 타입에 대응되는 printf 서식 지정자의 length modifier는 z이죠. 즉 printf("%zu",sizeof(pVoid));가 되어야 맞습니다.

서식 지정자 "%lu"unsigned long에 대응되는데, 이 타입이 size_t에 대응된다는 보장이 없습니다.
예컨대 win64에서 전자는 4바이트, 후자는 8바이트일 겁니다.

한편 void pointer의 크기가 int의 크기와 같다고 할 수도 없죠.
예컨대 x86_64 플랫폼에서 대개 전자는 8바이트, 후자는 보통 4바이트입니다.

(D) void pointer에 sizeof 연산자를 쓸 수 없다고 누가 그래요?

익명 사용자의 이미지

(void*)0이 아주 정석적인 null pointer constant라고 말씀 드린 건, 표준에서 정의한 null pointer constant에 완벽하게 부합된다는 의미입니다.

실무에서는 당연히 NULL을 사용하는 게 더 적절합니다.

whdtjr222의 이미지

파면 팔수록 새로운 것들이 나오는군요 감사합니다 더욱 노력하겠습니다

댓글 달기

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