LearnFrenzy
Sign in Take a free test

Typedef · Find the Error · Question 4

Error: re-pointing a const pointer-typedef variable Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

typedef char *String;

int main(void) {
    char a[] = "first", b[] = "second";
    const String s = a;
    s = b;
    printf("%s\n", s);
    return 0;
}
  • A a and b must be const
  • B const String is char *const: the pointer itself is const, so s = b is not allowed Correct
  • C String cannot point to an array
  • D There is no bug
Correct Answer: Option B

The programmer probably wanted read-only characters (const char *) but got a read-only pointer. Use typedef const char *CString; and then CString s = a; s = b; works.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links