我有这段代码func
我正在获取指向指针数组的指针。此函数的目的是将字符串写入两个分配的空间以进行chars
。在主中分配。我在这一行得到段错误
memcpy(*c[1],"hi",sizeof("hi"));
这是完整代码
void func(char (**c)[])
{
memcpy(*c[0],"hello",sizeof("hel"));
memcpy(*c[1],"hi",sizeof("hi"));
}
int main()
{
char (*arr)[2]=malloc(sizeof(char[2][10]));
func(&arr);
printf("%sn",arr[0]);
printf("%sn", arr[1]);
return 0;
}
我已经使用
char (*arr)[2]=malloc(sizeof(char[2][10]));
现在传递两个分配的字符串空间的地址,我像这样调用
func(&arr);
传递指针变量数组地址的要点arr
这样我可以看到main(...)
中字符串空间的更改,以及FUNC
中所做的更改
但是这条线引起了麻烦
memcpy(*c[1],"hi",sizeof("hi"));
赛段错误
谁能告诉我我做错了什么,这个答案也与指针数组有关。 https://stackoverflow.com/a/69551741/4808760
我期待的输出是
hell
hi
瓦尔格林德垃圾场
valgrind --leak-check=full -s ./a.out
==7397== Memcheck, a memory error detector
==7397== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7397== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info
==7397== Command: ./a.out
==7397==
==7397== Invalid write of size 2
==7397== at 0x4849F23: memcpy@GLIBC_2.2.5 (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==7397== by 0x1091F2: func (test.c:8)
==7397== by 0x10922A: main (test.c:18)
==7397== Address 0x54698dcdde89a700 is not stack'd, malloc'd or (recently) free'd
==7397==
==7397==
==7397== Process terminating with default action of signal 11 (SIGSEGV)
==7397== General Protection Fault
==7397== at 0x4849F23: memcpy@GLIBC_2.2.5 (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==7397== by 0x1091F2: func (test.c:8)
==7397== by 0x10922A: main (test.c:18)
==7397==
==7397== HEAP SUMMARY:
==7397== in use at exit: 30 bytes in 1 blocks
==7397== total heap usage: 1 allocs, 0 frees, 30 bytes allocated
==7397==
==7397== LEAK SUMMARY:
==7397== definitely lost: 0 bytes in 0 blocks
==7397== indirectly lost: 0 bytes in 0 blocks
==7397== possibly lost: 0 bytes in 0 blocks
==7397== still reachable: 30 bytes in 1 blocks
==7397== suppressed: 0 bytes in 0 blocks
==7397== Reachable blocks (those to which a pointer was found) are not shown.
==7397== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==7397==
==7397== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==7397==
==7397== 1 errors in context 1 of 1:
==7397== Invalid write of size 2
==7397== at 0x4849F23: memcpy@GLIBC_2.2.5 (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==7397== by 0x1091F2: func (test.c:8)
==7397== by 0x10922A: main (test.c:18)
==7397== Address 0x54698dcdde89a700 is not stack'd, malloc'd or (recently) free'd
==7397==
==7397== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
要解决代码的实际问题,请执行以下操作:
- 您不包括相关的标头。
char (*arr)[2]
错了。您希望它指向char [2][10]
的第一项。这是一个由 2 个项目组成的数组,其中每个项目是一个 10 个字符的数组。因此,指针应char (*arr)[10]
。func(&arr);
没有意义,没有理由通过引用传递指针,除非您打算更改指针本身(例如在函数中执行 malloc 时)。char (**c)[]
是无稽之谈。这是指向指向不完整数组类型的指针数组的指针。但是,不能将不完整的数组类型作为参数传递给函数。这应该是char str[2][10]
的,它作为参数"衰减"成等效的char (*str)[10]
。- 您不能在子字符串上使用 memcpy,因为它不会附加 nul 终止。如果使用memcpy,则必须在末尾手动添加