1

I want to write a function that returns a part of another array. Here's how I tried to implement it:

char *subarrayWithRange(char *array, int location, int length)
{
  char subarray[length];
  subarray = (array + location);
  return subarray;
}

When I try to compile it, clang gives me this error:

error: array type 'char [length]' is not assignable

Apparently, I can't assign an array to a sub-array of another array. But, this works when I define the subarray as a pointer:

char *subarrayWithRange(char *array, int location, int length)
{
  char *subarray;
  subarray = (array + location);
  return subarray;
}

Now, though, I can't define the length of the subarray. Is this a C language thing? Can I get around this somehow?

Ajay Tatachar
  • 383
  • 3
  • 16
  • You must initialize the array. Or assign to its individual elements. –  Jan 08 '14 at 11:05
  • look at this question [link](http://stackoverflow.com/questions/2137361/what-is-the-best-way-to-create-a-sub-array-from-an-exisiting-array-in-c) – Android Jan 08 '14 at 11:07
  • You could define your own Array struct and then return that. For example in APR you make an array with something like this: `apr_array_header_t *arr = apr_array_make(pool, 0, sizeof(const char *));` Do it a similar way for your own struct. – Brandin Jan 08 '14 at 12:53
  • Variable length arrays have been part of C since C99, that's not the problem. – Nigel Harper Jan 08 '14 at 11:37
  • I think they are allocated on the stack (like when you use `alloca`) and thus cannot be returned. – ThiefMaster Jan 09 '14 at 09:56

1 Answers1

4

You can't assign to arrays. You also can't return a local array, since the memory it uses goes out of scope when the function exits. You must use dynamic (heap) memory, using e.g. malloc() to allocate.

Also, you must terminate the sub-array if you intend it to be a valid string:

char * substringWithRange(const char *string, size_t start, size_t length)
{
  char *p = malloc(length + 1);
  if(p != NULL)
  {
    memcpy(p, string + start, length);
    p[length] = '\0';
  }
  return p;
}

Note that the above assumes that the length never exceeds the input length, since that is not being checked. You should probably add such checkings, and just truncate.

unwind
  • 391,730
  • 64
  • 469
  • 606