gpt4 book ai didi

c - strncpy() 在第二次调用同一源时失败

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

我是 c 的新手,想将字符串分成两部分。这是我的代码:

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

void test(char** a, char** b)
{
const char * c = "abcdef";

*a = (char *)malloc(4* sizeof(char));
*b = (char *)malloc(4* sizeof(char));


strncpy(*a, c, 3);

*a[3] = '\0';

fprintf(stderr, "a -> %s\n", *a);



strncpy(*b, c+3, 3);

*b[3] = '\0';

fprintf(stderr, "b -> %s\n", *b);

}

int main()
{
setvbuf (stderr, NULL, _IONBF, 0);
char *a = NULL;
char *b = NULL;

test(&a, &b);

fprintf(stderr, "a -> %s\n", *a);
fprintf(stderr, "b -> %s\n", *b);
}

我想在 a 变量上有 abc,在变量 b 上有 def。但我的问题是它因 Segmentation Fault 而失败。运行此命令后,我得到以下输出:

a -> abc
Segmentation fault

我不明白为什么。我正在使用 cygwin 并使用命令构建它

gcc test.cpp -o test.exe

抱歉,如果问题听起来很愚蠢。谢谢。

最佳答案

数组下标运算符 [] 的优先级高于解引用运算符 *

所以你想改变

*a[3] = ...

成为

(*a)[3] = ...

b 也是如此。


将编译器的警告级别设置得足够高,它应该就此警告您。或者至少告诉过你他们的东西有问题

*a[3] = '\0';

关于c - strncpy() 在第二次调用同一源时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46620060/

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