gpt4 book ai didi

c - 调用 strcpy 时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:45 27 4
gpt4 key购买 nike

我尝试使用 strncpy 然后使用 strcpy 反之亦然,但我在运行时一直收到段错误。我以为这是因为函数中的逻辑错误,但我调换了它们的位置,只有第一个会执行。

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

int main(void)
{
char c = ' ', sentence[50], *pointer_to_string;
pointer_to_string = &sentence[0];
int index = 0;

printf("Please enter a sentence:");
while ((c = getchar()) != '\n')
{
sentence[index] = c;
index++;
}
sentence[index] = '\0';

char *string_copy1, *string_copy2;

strncpy(string_copy1, pointer_to_string, 5);
printf("strncpy(string_copy1, pointer_to_string, 5):\n");
printf("%s\n", string_copy1);

strcpy(string_copy2, pointer_to_string);
printf("strcpy(string_copy2, pointer_to_string):\n");
printf("%s\n", string_copy2);
}

最佳答案

参见 documentation :

char *strcpy(char *dest, const char *src);

第一个参数是指向目标缓冲区的指针。但是你的指针没有初始化:

char *string_copy1, *string_copy2;

因此,指针包含一些垃圾值。而strcpy()写入不属于你程序的内存。它导致segmentation fault .

char string_copy1[50] = { 0 };
char string_copy2[50] = { 0 };

用零填充它们是必要的,以避免 strncpy() 出现问题:

If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

关于c - 调用 strcpy 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com