Question

Can someone please help me with this function.

char *repeat(char *s, int x)

Returns a new string consisting of the characters in s repeated x times. For example, if s is the string all right , the function returns the new string all right all right all right. If s is NULL, the function returns NULL.

It is up to the caller to free any memory allocated by the function.

This is what I have so far...

char *repeat(char *s, int x){

int i;
int count = 0;

while(s[count] != '\0')
{
    count++;
}

int repeat = count * x;
char *newArray = malloc(5000);

for(i = 0; i < repeat; i++)
{   
    while(*s != '\0')
        *newArray++ = *s++;     
}

return (char*)newArray;

}

Was it helpful?

Solution

char *repeat(const char *s, int x){
    if(s){
        int i, count = 0;

        while(s[count] != '\0'){
            ++count;
        }

        char *newArray = malloc(count * x + 1);
        if(newArray){
            char *na = newArray;
            for(i = 0; i < x; ++i) {
                const char *p=s;
                while(*p)
                    *na++ = *p++;
            }
            *na = '\0';
        }
        return newArray;
    } else {
        return NULL;
    }
}

OTHER TIPS

The main issue--assuming you're only getting one copy back--is that you need to "reset" the pointer s between your copies. Right now, you hit the end of s, so the successive iterations are trying to copy a string of "\0".

Two potential other problems (for the future) are:

  • You should be using (I'm guessing you know this one and aren't allowed to do otherwise) strcpy() to do the copying.
  • Memory should always be allocated by the function's caller. The pointer to the new string goes on the call stack and the memory goes on the heap technically assigned to repeat(), so when you return, the run-time is under no obligation to preserve any of it for the caller to use. It "usually works," but it can be painfully dangerous.

First allocate memory then copy/move the memory. For your reference, a simple one(not fully test):



char *repeat(char *s, int x)
{
    char *result = malloc(sizeof(s) * x + 1);

    while (x > 0) {
        strcat(result, s);
        x --;
    }

    return result;
}
int main(int argc, const char * argv[])
{

    // insert code here...
    char *sample = "hell";
    char *result = repeat(sample, 3);


    printf("result : %s\n", result);

    free(result);
    return 0;
}

You'd better:

  1. don't forget x should be the integer and greater than 0;
  2. always remember to free the created string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top