-3

I have a question on adding strings and data types. What does it mean to use them in such arithmetic? Does body + size mean that it is creating a new block of memory that includes both of them?

The following is just an excerpt of the code:

char* body;
ssize_t size = load();
char buffer[512];

    body = realloc(body, size + octets);
        if (body == NULL)
        {
        return -1;
        }
        memcpy(body + size, buffer, octets);
        size += octets;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Jessup Jong
  • 31
  • 1
  • 1
  • 6

1 Answers1

1
char *body;

body is not a string, it's a pointer. If it's initialized appropriately, it might point to a string, but it's not a string itself.

ssize_t size;

size is an integer.

body + size

This is pointer arithmetic. It doesn't allocate any memory; it merely takes a pointer value and an integer, and yields a new pointer value. If body points to an element of an array, then body + size points to an element size positions later in the same array. (If body doesn't point to an array element, or if body + size is outside the bounds of the array, then the behavior is undefined.)

memcpy(body + size, buffer, octets);

For example, suppose body points to the initial (0th) element of an array of 100 char elements, and suppose size == 30. Then body + size is a char* value pointing element 30 of the same array.

Look up "pointer arithmetic" in any decent C textbook or tutorial.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631