Since you don't intend to modify the contents of st
, go ahead and declare it as const
. Since you intend to allocate a new string in your function, you should return it to the caller.
char *repeat(const char* st,int n){
k
is unnecessary for your problem. Call the standard functions.
int i,l=strlen(st);
char* ptr;
Don't cast the result of malloc
, as this can mask a fatal error in C. sizeof(char)
is always 1. Check the result of the malloc
call for success.
ptr=malloc(n+1);
if (ptr == NULL) return NULL;
for (i=0;i<n;i++){
Access arrays idiomatically with []
. Note that k
increments whenever i
does, but you are applying a modulo operation of k
. However, C has a modulo operator, which you can use directly on i
.
ptr[i]=st[i%l];
}
Make sure the new string is NUL
terminated. Your function is declared to return a result, but your implementation fails to do so.
ptr[n] = '\0';
return ptr;
}
C has many functions you can call to do the copying for you rather than the byte by byte loop you have written. There is simplicity in your implementation, but below is an alternative, that also includes additional error checking that is lacking in your solution.
(Some may balk at the use of sprintf
, but it is being used correctly.)
char *
repeat (const char *st, int n) {
int l = st ? strlen(st) : 0;
char *ret = (st && n > 0 ? malloc(n+1) : 0), *p = ret;
while (ret && n > 0) {
p += sprintf(p, "%.*s", (l < n ? l : n), st);
n -= l;
}
return ret ? ret : "(nil)";
}
Try it online!