I have a problem to divide the string into smaller strings, which have 3 char form the main string. I want to put the small strings into the field of pointers. I am doing something like this, but it is completly wrong:
1 2 3 4 5 6 7 8 9 10 11 12 13
char *str = "hello world";
int i = strlen(str);
char **str2 ;
str2 = newchar*[i];
if(i > 3)
{
for(int a = 0, b = 0; a<i; b++ ) {
strncpy(str2[b], str+a, 3);
a =a+3;
}
}
Could anyone explain me, how to do that properly, and why this doesnt work? Thank you.
If you must use char[]... try creating a function to get the job done. Give it a starting and ending position (left-inclusive) and, starting from that position and cycling in a for loop as long as your counter is less than the end position, copy the characters into a return array of a length equal to the difference between those two, plus one for the null.
Got that? (I mean this last line humorously because I know how long that is and how difficult it may be to read.)
I think the problem with your code is simply that you wrote the strcpy() wrong. Well, that and the fact that you didn't allocate any memory for str2[b].
Your strcpy_s() should be strcpy_s(str2[b],&str[a],4); (str+a == str[a], which is of type char, while strcpy_s (or strncpy) requires a second argument of type char*). Actually, I can't rememeber if the size_value is the second or third argument... anyways. And the size_value has to be equal to 4 because you want three characters + '\0' at the end of your c-string.
And allocate memory fo str2[b]. That always helps, too.
No Blackoder, what you wrote, is only returning one symbol, and I wanted to return 3 symbols. I used char** because its a pointer to field of pointers, isn it? And its content should by like this:
1 2 3 4
hel //str2[0]
lo //str2[1]
wor //str2[2]
ld //str2[3]
And Wasabi, didnt I allocate memory for str2[b] if I allocated the memory for str2? Or was it only for that pointer, which points to another pointers?