Nope, you don't got it:
Code:
#include<stdio.h>
#include<conio.h> // I sincerely hope you're not still using Turbo C. If so, time to upgrade.
// Pelles C, Code::Blocks with MinGW or even MSVC++ Express are much better, free options
#include<string.h>
#include<stdlib.h>
char* Repeat(char *s,int n)
{
if(n==0) {
return " "; // this is not the empty string, it's a string with one space. "" is the empty string (two double " with nothing between them)
}
char *a=(char*)malloc(2*sizeof(s)); // This line mallocs a new string every time, so you throw away the old ones. This is a memory leak.
// You also mallco the wrong size. s is a char *, which always has the same size (probably 4 or 8 bytes).
// I can't reliably repeat a string like "ABCDEFGHIJKLMNOPQRSTUVWXYZ" more than a few times. Try it yourself.
// Your malloc here needs to be based on strlen(a) from main (the length of the original string to repeat)
strcat(a,s);
char* p=Repeat(a,n-1);
strcat(a,p);
return a;
}
int main(void) // Can't hurt to be explicit here.
{
char a[]="Hello";
char *b;
int n;
printf("Enter the no of times u want to repeat\n");
scanf("%d",&n);
b= Repeat(a,n);
printf("%s",b);
getchar();
return 0; // Main is supposed to return an int, so make it do so.
}
There are copious other errors. Your code is still quite broken. I don't think you fully followed my advice in post #7. Did you work this out by hand and do several examples on paper?