MH1993 MH1993 - 1 month ago 13
C Question

A simple C exercise going wrong: Trying to return a pointer to an array of two strings

"Return a pointer to an array of two strings. The first is the characters
of string s that are at even indices and the second is the characters from
s that are at odd indices"

char **parity_strings(const char *s) {

char** parity = malloc(sizeof(char*) * 2);
char even_strings[] = "";
char odd_strings[] = "";
int x = 0;
int y = 0;

for (int i = 0; i < strlen(s); i++) {

if ((i % 2) == 0) {

even_strings[x] = s[i];
x++;
}
else {
odd_strings[y] = s[i];
y++;
}
}

parity[0] = even_strings;
parity[1] = odd_strings;



return parity;

}

int main(int argc, char **argv) {
char **r = parity_strings(argv[1]);
printf("%s %s %s", r[0], r[1], argv[1]);
return 0;
}


My logic makes sense but the output is always incorrect. For example, with input "ababab" I get back "ababab" while the expected output is "aaa bbb ababab". What did I do wrong?

Answer

The string named even_strings is a local variable, so its memory will be freed after your function returns, so it is not valid to try to return a pointer to it to the caller.

Try changing this line:

char even_strings[] = "";

to something like this:

char * even_strings = malloc(some_size);

The same goes for your odd_strings string.

Also, be sure to pick a good value for some_size so that your program allocates enough memory for each string so that it can hold all the data you are writing to it.