#include<stdio.h>
#include<string.h>
void recurse(char [],const char *);
int main() {
        char *charset="abcdefghij";
        recurse("",charset);
}
void recurse(char str[],const char *charset) {
    int len;
    len=strlen(str);
    strcat(str,charset[len+1]);
    if(len<strlen(charset))
        recurse(str,charset);
    printf("%s",str);
}

Like the question says, what is wrong here? This is the logic of my program
1. Keep a string called charset which I can fill any amount of numbers, characters
2. The first digit should first be passed to printf (or) any function I make, then the 1st two digits followed by first three, all the way till the the strlen of the passed string is same as that of the charset

I heard that if i use a function like with a global variable charset having A,B,C,D,etc.

void somefunction(char str[]) { //str is initialized here as "String"
    for(int i=0;i<5;i++) {
        calledfunction(strcat(str,charset[i])); // Here the string goes as "StringA"
    }
    anotherfnction(str); // Here the string goes as "String"
}

newbie at C.. do help me fix this..

Dani AI

Generated

your approach is close, but two things trip you up: (1) you are indexing past the start of the set, so the first character never gets appended and the last access walks off the end, and (2) you print after the recursive call, which reverses the order. If you want to see "a", then "ab", then "abc", print before you recurse. Also, to append a single character, do not pass a character where a string is expected; either write directly into a writable buffer and NUL-terminate, or use a function that limits the append to one byte.

If you do not actually need recursion, this tiny loop prints the successive prefixes without any extra buffer or mutation:

#include <stdio.h>
#include <string.h>

void print_prefixes(const char *cs) {
    size_t n = strlen(cs);
    for (size_t i = 1; i <= n; ++i)
        printf("%.*s\n", (int)i, cs);
}

If you do want recursion that truly "postpends" one character at a time, keep a mutable buffer and write the next character in place. This prints in the forward order and avoids off-by-one issues:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static void print_prefixes_rec(const char *cs, size_t n, size_t i, char *buf) {
    if (i == n) return;
    buf[i] = cs[i];       // append one char
    buf[i + 1] = '\0';    // keep it terminated
    puts(buf);            // "a", then "ab", then "abc", ...
    print_prefixes_rec(cs, n, i + 1, buf);
}

int main(void) {
    const char *charset = "abcdefghij";
    size_t n = strlen(charset);
    char *buf = calloc(n + 1, 1);   // writable buffer of exact size
    print_prefixes_rec(charset, n, 0, buf);
    free(buf);
}

This keeps indexing and capacity explicit, prints in the intended order, and avoids relying on concatenation of strings for single characters. and are right that simpler loops work; the recursive version above keeps your original flavor while being safe and predictable.

Recommended Answers

All 4 Replies

I think you can not add characters to empty string passed to function in C.

This would seem to work:

#include<stdio.h>
#include<string.h>
void recurse(const char *, int);
int main() {
        const char *charset="abcdefghij";
        recurse(charset, strlen(charset));
}
void recurse(const char *charset, int len) {
    int i;
    if(len>1) recurse(charset, len-1);
    for(i=0; i < len; i++) printf("%c", charset[i]);
    printf("\n");
}

@pyTony: that logic occured to me earlier but doesnt solve the problem. Here again your printing with respect to the length rather than postpending the character to the string. Well, thanks anyways..! I will figure this out somehow :)

The original code was in PHP, converting to C is such a pain in the a** X_x. Thanks a Lot

Why not simple for loop, if recursion is not the task? I don't really get your problem. If you could give example of failure maybe I would get it.

I agree with pyTony, recursion seems like an odd way to solve this problem. However, you should be able to get your original version to work if you give it an array that can be modified (untested):

int main(void) {
    char *charset="abcdefghij";
    char buffer[100] = "";
    recurse(buffer,charset);
}

When you call recurse("", charset) the "" is a 1-byte character array in (probably) read-only memory. You can't strcat to it or modify it in any way without invoking undefined behavior.

I heard that if i use a function like with a global variable charset having A,B,C,D,etc.

\<code snipped>

You heard wrong then. strcat() modifies its first argument permanently. (This is not the case in e.g. Java, where strings are immutable and concatenation returns a newly created string.) strcat(3)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.