问题描述
我正在使用两个uint8_t指针
uint8_t *A_string = "hello"
uint8_t *B_string = "world"
我正在尝试使用strcat将这两者连接起来
strcat(A_string,B_string);
我收到一条错误消息,说“ uint8_t与char * restrict 类型的参数不兼容”
因此,我将A_string和B_string都强制转换为char *并尝试了。现在我没有得到错误,但是串联没有发生。
任何人都可以让我知道如何对两个uint8_t *类型的字符串进行转换吗?
解决方法
A_string
指向不可修改的string literal。但是,strcat
的第一个参数不能是指向字符串文字的指针—它必须是指向可修改数组的指针,而且该数组必须足够大以容纳串联的结果。
要解决此问题,请将A_string
声明为足够大的数组。
此外,请注意编译器警告:您的代码中潜在的符号不匹配可能会导致问题。实际上,您可能想在这里使用char
而不是uint8_t
。
这是固定版本:
#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);
}
实际上,您通常不会对数组大小进行硬编码,因为如果知道,您也可以自己在源代码中连接字符串文字。
相反,您需要计算所需大小,并使用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,result);
}