#include<stdio.h>
#include<string.h>
int main()
{
unsigned char *s;
unsigned char a[30]="Hello world welcome";
memcpy(s,&a,15);
printf("%s",s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个分段错误.请帮我修复此错误
Mys*_*ial 11
你需要为内存分配s.就目前而言,它只是一个未初始化的指针(很可能)指向任何地方:
unsigned char *s = malloc(16);
Run Code Online (Sandbox Code Playgroud)
和所有内存分配一样,当你使用它时它应该被释放:
free(s);
Run Code Online (Sandbox Code Playgroud)
编辑:另一个错误(我忽略了)是你需要在调用后终止NULL memcpy.
memcpy(s,a,15);
s[15] = '\0';
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用strcpy(),并将字符串截断为15个字符,但您需要分配足够的内容来存储所有字符串a(包括其NULL终止符):
unsigned char a[30]="Hello world welcome";
unsigned char *s = malloc(strlen(a) + 1); // Allocate
strcpy(s,a); // Copy entire string
s[15] = '\0'; // Truncate to 15 characters by inserting NULL.
printf("%s",s);
free(s); // Free s
Run Code Online (Sandbox Code Playgroud)