0

I'm new to c, I have the following strings:

char* content = realloc(NULL, sizeof(char) * 10);
char line [256];

I want to append like:

content +=line;

but this gives error: expression must have integral type'

Devy
  • 703
  • 6
  • 17

1 Answers1

3

There's a few things to note about your code...

First of all, the expression realloc(NULL, sizeof(char) * 10) is equivalent to malloc(10) (sizeof(char) is specified to always be equal to 1).

Secondly, C doesn't have any kind of dynamic arrays. If you want to append one array to another, then you need to make sure the destination can fit itself plus the other array.

Thirdly, to append two null-terminated byte strings (normal "strings" in C) you use the strcat function. As in

strcat(content, line);

But you can only do that if there's enough space allocated for content that the full concatenated string will fit. And that both content and line are both null-terminated byte strings.


To put it all together for your code, it could be something like this

// The initial length of content
#define CONTENT_LENGTH  10

// Allocate some memory
char *content = malloc(CONTENT_LENGTH);

// Copy a string to the newly allocated memory
strcpy(content, "foobar");

// Create an array and initialize it
char line[256] = "hoola"

// To concatenate the two strings, we first need to make sure it can all fit
// in the memory for content, otherwise we need to reallocate it
// Note the +1 in the calculation: It's to account for the null terminator
if (strlen(content) + strlen(line) + 1 > CONTENT_LENGTH)
{
    // Not enough space, need to reallocate the memory
    char *temp_content = realloc(content, strlen(content) + strlen(line) + 1);
    if (temp_content == NULL)
    {
        printf("Could not allocate memory\n");
        exit(EXIT_FAILURE);
    }

    // Reallocation successful, make content point to the (possibly) new memory
    content = temp_content;
}

// Now we can concatenate the two strings
strcat(content, line);

// And print it (should print that content is foobarhoola)
printf("content = %s\n", content);

Some parts of this could of course be separated into its own function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621