Interview Questions

This code, straight out of a book, isnt compiling

C Interview Questions and Answers


(Continued from previous question...)

This code, straight out of a book, isnt compiling

Q: This code, straight out of a book, isn't compiling:
int f()
{
char a[] = "Hello, world!";
}

A: Perhaps you have an old, pre-ANSI compiler, which doesn't allow initialization of ``automatic aggregates'' (i.e. non-static local arrays, structures, or unions). You have four possible workarounds:

1. If the array won't be written to or if you won't need a fresh copy during any subsequent calls, you can declare it static (or perhaps make it global).

2. If the array won't be written to, you could replace it with a pointer:
f()
{
char *a = "Hello, world!";
}


You can always initialize local char * variables to point to string literals.

3. If neither of the above conditions hold, you'll have to initialize the array by hand with strcpy when the function is called:
f()
{ char a[14];
strcpy(a, "Hello, world!");
}

4. Get an ANSI-compatible compiler.

(Continued on next question...)

Other Interview Questions