Concatenation of two uint8_t pointer

2.4k views Asked by At

I am using two uint8_t pointers

uint8_t *A_string = "hello"
uint8_t *B_string = "world"

And I am trying to concatenate both these using strcat

strcat(A_string, B_string);

I am getting an error saying "uint8_t is incompatible with parameter of type char* restrict"

So I type casted both A_string and B_string to char* and tried . Now I am not getting the error but the concatenation is not happening .

Can anyone please let me know how do I convatenate two strings which are of type uint8_t * ?

1

There are 1 answers

1
Konrad Rudolph On BEST ANSWER

A_string points to an unmodifiable string literal. However, the first argument of strcat mustn’t be a pointer to a string literal — it must be a pointer to a modifiable array, and furthermore the array must be large enough to hold the result of the concatenation.

To fix the issue, declare A_string as an array of sufficient size.

Furthermore, heed the compiler warnings: you have a potential signedness mismatch in your code that might cause problems. In fact, you probably want to use char instead of uint8_t here.

Here’s a fixed version:

#include <stdio.h>
#include <string.h>

int main(void) {
    // 11 = strlen("hello") + strlen("world") + 1
    char a_string[11] = "hello";
    char const *b_string = "world";
    strcat(a_string, b_string);

    printf("%s\n", a_string);
}

In reality you usually wouldn’t hard-code the array size since if you knew it you could just as well concatenate the string literals yourself in the source code.

Instead you’d need to calculate the requires size, and dynamically allocate a buffer of sufficient size using malloc:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    char const *a_string = "hello";
    char const *b_string = "world";
    
    size_t total_len = strlen(a_string) + strlen(b_string) + 1;
    char *result = malloc(total_len);
    if (! result) {
        fprintf(stderr, "Unable to allocate array of size %zu\n", total_len);
        exit(1);
    }
    strcpy(result, a_string);
    strcat(result, b_string);

    printf("%s\n", result);
}