views:

100

answers:

1

Hey fellas...

OK, a recent quiz entry tasked the student with writing a method 'longhead' (char *longhead) that would return a string consisting of the concatenation of all of the heads in a given string. Example:

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

OUTPUT: tththithis

I did come up with a solution, but it works with arrays only and it's inside the main method. I've been trying to really get a good foothold on pointers, and I feel that by repeating these quiz questions I'll definitely get to the right place.

Is there a solution to this? Alternatively...could this be done just using 'strlen'?

UPDATE:

Here's the solution I wrote that works with a char array only, and is inside of a 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]);
}
+4  A: 

The length of the desired string (when the input is of length N) is (N * (N+1)) / 2 (sum of integers 1 to N, sometimes known as "Gauss's formula"). So...:

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;
}

Of course the caller has to take responsibility for the result (free it when done): the example calling code you give would cause a memory leak, inevitably.

Alex Martelli