【发布时间】:2020-10-20 21:58:06
【问题描述】:
我在 C 中创建了一个小函数,它复制了一个 char 数组。我不想source被改变,所以我把const放到函数声明和函数体中,但是它改变了。
main.c
#include "copy_char.h"
#include <stdio.h>
int main(void)
{
char source[] = { 'h', 'e', 'l', 'l', 'o', 0 };
char dest[] = { 'a', 'b', 'c', 0 };
printf("%s\n", source); // hello
printf("%s\n", dest); // abc
copy_char(source, dest);
printf("%s\n", source); // o (?) - why did this change?
printf("%s\n", dest); // hello
}
copy_char.c
#include "copy_char.h"
void copy_char(const char* source, char* dest)
{
while(*source != 0)
{
*dest++ = *source++;
}
*dest = 0;
}
copy_char.h
#ifndef COPYCHAR_H
#define COPYCHAR_H
void copy_char(const char* source, char* dest);
#endif /* COPYCHAR_H */
谁能给我解释一下,为什么我的source char 数组从hello 变成了o?
【问题讨论】:
-
您有未定义的行为,因为您溢出了
dest缓冲区。