海湾合作委员会 4.4.3 c89
我有以下源文件。
但是,我在以下行中得到堆栈转储:
printf("dest: %d [ %s ]\n", i, dest[i]);
原因是if退出for循环失败。我在 for 循环中尝试了不同的条件来尝试在打印之前中断。
i != NULL
i != '\0'
i != 0
然而,上述所有方法均无效。我可以使用 sizeof(src) 作为条件。但我只想知道为什么我会使用当前方法获取此堆栈转储。
当我使用 gdb 检查时,所有数组元素都已初始化为 nul:
(gdb) p dest
$8 = {0x0 <repeats 11 times>}
源代码:
void copy_characters()
{
/* static character array */
char src[] = "sourcefile";
/* array of pointers to char */
char *dest[sizeof(src)] = {0};
size_t i = 0;
/* Display the source characters */
for(i = 0; src[i] != '\0'; i++) {
printf("src [ %c ]\n", src[i]);
}
/* Copy the characters */
for(i = 0; i < sizeof(src); i++) {
dest[i] = &src[i];
}
/* Display them */
for(i = 0; dest[i] != '\0'; i++) {
printf("dest: %d [ %s ]\n", i, dest[i]);
}
}
非常感谢您的任何建议,
最佳答案
首先 - 我不确定您要在这里做什么。但是:
dest[i]
是一个指向字符的指针。
您应该测试dest[i]
指向的值是否为空,如:
for(i = 0; *(dest[i]) != '\0'; i++) {
关于c - 将字符复制到 char 指针数组时的堆栈转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3511173/