Sunday, April 29, 2007

Cute C/C++ puzzles from meebo

since I couldn't run Yahoo! Messenger, I went to Meebo and curiously browsed at their jobs page. (yeah, right)

anyway, they are hiring c/c++ developers and had these nifty little c/c++ questions that tests if you're alright for the job. Here were the samples.

Puzzlers! Try these out :)

1. With these variable declarations: int i, j[10], *k;
Which of the following are legal?

a. i = *(&(j[2]) + 1);
b. k = &(j[1]);
c. i = &(j[2]) + 1;

2. Assuming the function lookupName is defined, what’s wrong with this code (hint: 2 bugs)?

const char *getName(const char *c) {
std::string name = lookupName(c);
if (name == NULL)
return "Anonymous";
return name.c_str();
}


int main(int argc, char *argv[]) {
const char *name = NULL, *c = NULL;
if (argc >= 2)
c = argv[1];
name = getName(c);

printf("My name is %s\n", name);
return 0;
}

3. What’s wrong with this program? If you were to fix it, what would the intended output be?

void swap(char *str, int index1, int index2) {
char tmp = str[index1];
str[index1] = str[index2];
str[index2] = tmp;
}

int main(int argc, char *argv[]) {
char *planet1;
char *planet2;

planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;

snprintf(planet1, 7, "Jupiter");
planet2 = "Saturn";

swap(planet1, 0, 3);
swap(planet2, 3, 4);

printf("results: %s and %s\n", planet1, planet2);
return 0;
}

yes, I'm so geeky. but it looks fun. :)

No comments:

Post a Comment