Reputation: 81
I want to write a programm, which can print all possible strings of length k that can be formed from a and b.
Example for k = 3: aaa, baa, aba, bba, aab, bab, abb, bbb.
My code isn't working. Can somebody please correct me? Thank you.
#include <stdio.h>
void abcombirec(char prefix[], int k) {
char ab[] = {'a', 'b'};
if (k == 0) {
printf("%s\n", prefix);
return;
}
for (int i = 0; i < 2; i++) {
newprefix = prefix + ab[i];
abcombirec(newprefix, k - 1);
}
}
void abcombi(int k) {
char str[] = "";
abcombirec(str, k);
}
int main() {
(abcombi(3));
return 0;
}
Upvotes: 3
Views: 96
Reputation: 64702
I wrote a quick-n-dirty recursive function:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void showboth(char* txt, int pos)
{
if (pos == strlen(txt)-1)
{
printf("%s\n", txt);
txt[pos] = 'b';
printf("%s\n", txt);
txt[pos]='a';
}
else
{
showboth(txt, pos+1);
txt[pos] = 'b';
showboth(txt, pos+1);
txt[pos] = 'a';
}
}
int main(void) {
char text[5] = "aaa";
showboth(text, 0);
return 0;
}
Success #stdin #stdout 0s 4256KB
aaa
aab
aba
abb
baa
bab
bba
bbb
Upvotes: 0
Reputation: 726699
Your code assumes that C "understands" operator +
plus as a concatenation:
newprefix = prefix + ab[i];
However, that is not what is happening: C understands this expression as pointer arithmetic, interpreting ab[i]
as an integer offset.
Concatenating a character to a string in C requires considerable amount of code:
Here is how this looks in code:
size_t len = strlen(prefix);
char tmp[len+2];
strcpy(tmp, prefix);
tmp[len] = ab[i];
tmp[len+1] = '\0';
The rest of your code is fine; with this one change in place, your code produces the results that you expected (demo).
Note: this code allocates tmp
in automatic memory. Considering what the code does, k
would be pretty small (otherwise the code would run for a really long time) so array allocations in automatic memory wouldn't be a problem. However, you need to be very careful with this approach, because you can easily cause undefined behavior if len
is too large. You should use more secure version of strlen
and go for dynamic memory allocation in any scenario that goes into production.
Upvotes: 4