The strange behaviour doesn't have anything to do with whether your strings have upparcase letters or not. Your termination condition for the loop in stringToArray
is wrong:
int l = findLength(string);
while (string[i] != l) ...
The condition should be
while (i < l) ...
or, as you have already used in findLength
:
while (string[i] != '\0') ...
Because the condition is wrong – l
is 16 in your case and none of the letters have an ASCII value of 16 – you go beyond the valid bounds of the string, which leads to undefined behaviour.
At the moment, you just copy the old string to the new one, albeit in a very strange fashion. Your inner loop makes use of three variables, of which it increments two. That's very confusing. It probably also doesn't do what you think, because the condition:
if (string[i] == c || string[i] != '\0') ..
is true for all letters of the string, provided that the opuer loop should consider only valid characters up to, but not including the end of the string.
Finally, if you want to copy the string, you should allocate süpace for the terminating character:
char *str = malloc(l + 1);
When you want to append the final null character:
str = '\0';
You actually set the while allocated string to null, which leads to a memory leak. (The free
in main
doesn't produce an error, because free
can legally take ´NULL` as argument.) Instead, use:
str[l] = '\0';
With these fixes, you now have a program that copies the original string. The (POSIX) library function strdup
does this more effectively. If you want to return an array of strings, you must reflect your function to return a pointer to pointers of chars.
Below is a possible implementation of that behaviour. (It uses the approach to allocate memory for everything on the heap. If you always expect three short strings that may not be the best solution.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **stringToArray(const char *str)
{
char **res;
const char *p = str;
int n = 0;
while (p) {
p = strchr(p, ',');
if (p) p++;
n++;
}
res = malloc((n + 1) * sizeof(*res));
p = str;
n = 0;
while (p) {
const char *begin;
size_t len;
while (*p == ' ') p++;
begin = p;
p = strchr(p, ',');
if (p) {
len = p - begin;
p++;
} else {
len = strlen(begin);
}
res[n] = malloc(len + 1);
memcpy(res[n], begin, len);
res[n][len] = '\0';
n++;
}
res[n] = NULL;
return res;
}
int main(int argc, const char * argv[])
{
char *str = "Vermilion, Ultramarine, Chartreuse";
char **res = stringToArray(str);
int i = 0;
for (i = 0; res[i]; i++) {
puts(res[i]);
free(res[i]);
}
free(res);
return 0;
}