C - combine all thread heads

OK, a recent quiz entry set the student to write a longhead method (char * longhead), which returns a string consisting of concatenating all the heads in a given string. Example:

char *string = "this";
printf("%s\n", longhead(string));

OUTPUT: tththithis

I came up with a solution, but it only works with arrays and inside the main method. I actually tried to get a good hand on pointers, and I feel that by repeating these quiz questions I will definitely get to the right place.

Is there a solution? Alternatively ... can this be done only with 'strlen'?

UPDATE:

Here the solution I wrote works only with char array and is inside the main method:

char *toPrint = "roses";
int i, j = strlen(toPrint); 
char toPrintArray[j];
for(i = 0; *toPrint != 0; toPrint++, i++){
    toPrintArray[i] = *toPrint;
}
int k;
for(i = 0; i < j; i++){
    for(k = 0; k < i; k++)
        printf("%c", toPrintArray[k]);
}
+3
source share
1

( N) (N * (N+1)) / 2 ( 1 N, " " ). ...

char* longhead(const char* s)
{
    int len = strlen(s);
    char * result = malloc(1 + (len * (len+1))/2);
    char * p = result;
    int i;

    for(i=1; i<=len; ++i) {
      memcpy(p, s, i);
      p += i;
    }
    *p = 0;

    return result;
}

, (free , ): .

+5

Source: https://habr.com/ru/post/1719245/


All Articles