0
votes

I'm trying to write a program that takes puts even and odd indices of a string into their own arrays (with null-terminators at the end of each), which are stored in one array:

char **result = malloc(sizeof(char*) * 2);
int a, b = 0;
int index = strlen(s) / 2;
if (strlen(s) % 2 == 1) {
    result[0] = malloc(sizeof(char) * (index + 2));
    result[1] = malloc(sizeof(char) * (index + 1));
    result[0][index + 1] = "\0"; // 1
    result[1][index] = "\0";     // 2
} else {
    result[0] = malloc(sizeof(char) * (index + 1));
    result[1] = malloc(sizeof(char) * (index + 1));
    result[0][index] = "\0"; // 3
    result[1][index] = "\0"; // 4
}
for (int i = 0; i < strlen(s); i++) {
    if (i % 2 == 0) {
        result[0][a] = s[i];
        a++;
    } else {
        result[1][b] = s[i];
        b++;
    }
}
return result;

When I compile it, the commented lines get the warning "assignment makes integer from pointer without a cast". I don't understand what's wrong with this code. Help?

1
Note that int a, b = 0; sets b to zero, but leaves a uninitialized. The compiler should be warning you about that, too. - user3386109

1 Answers

1
votes

In this following assignment -

result[0][index + 1] = "\0"; // 1
result[1][index] = "\0";     // 2

Use single quotes ' ' and not double quotes .

"" are use for string literals where as result[1][index] and similar are char , therefore , you get the warning.

result[0][index + 1] = '\0';      /*  <-- assigning character   */