Hey guy's. Can't get this seemingly simple function to work. It is suppost to get a string and return the first 10 characters, than the next time you call it, it returns the second 10 cheracters and so on. I did this in basic a while ago without problems, C seems more stubborn.

char *extract(int *pos, char *array) {
/* This function extracts 10 didget's at a time from 'array'. */
  char output[11] = {0};
  int max = (*pos) + 10, count = 0;
  
  while(*pos != max) {
    output[count] = array[*pos];
    count++;
    (*pos)++;
  }
  return *output;
}

And I called it with:

int pos = 0;
char *string = "BlahBlahBlahBlahBlahBlah......";
extract(&pos, string);
extract(&pos, string);

It exits with a segment fault. Thanks for any input.

Recommended Answers

All 4 Replies

return *output;

That line is really the whole problem. *output is not a pointer to char, it's a char. You're also trying to return a pointer to a local array. When the function returns, the local array goes bye bye and you can't use a pointer to it anymore.

Try passing the temporary array in as a parameter and return it at the end. That way you don't have to worry about it going out of scope:

char *extract(char output[11], int *pos, char *array) {
    int max = *pos + 10, 
        count = 0;

    while (*pos != max) {
        output[count] = array[*pos];
        count++;
        (*pos)++;
    }

    return output;
}

int pos = 0;
char *string = "BlahBlahBlahBlahBlahBlah......";
char output[11] = {0};

puts(extract(output, &pos, string));
puts(extract(output, &pos, string));
commented: Lots of help. Thanks +2
char *extract(int *pos, char *array)

static   char output[11] = {0};
  int max = (*pos) + 10, count = 0;

     // Need a terminator detection or will overrun the buffer
    // on last 10 character run if fewer then 10 chars!
   while(( 0 != array[*pos] ) && (*pos < max)) 
  {
    output[count] = array[*pos];
    count++; 
   (*pos)++;
  }

  return output;
}

NOTE: It makes code ugly by continuosly using contents of pointer
(*pos) for an integer.
instead copy the integer to a local variable and copy back the solution.

unsigned int nCnt = *pos;

           use nCnt

*pos = nCnt;
commented: Lot's of help. Thanks +2

One of the problems I see is this

return *output;

It is actually returning output[0] here when you want it to return the address of output array.
It should just be

return output;

Sorry fellows Daniweb is loading too slow on my side so when I was posting I couldn't see your replies... ;)

commented: Thanks anyway ;-) +2

Thanks guy's.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.