【发布时间】:2021-12-29 19:45:52
【问题描述】:
我想创建一个函数,它接受一个字符串文字和一个数组,并将字符串文字的字符复制到数组中。您能否告诉我以下代码中的问题是什么? 此代码的输出只是带有一些空格(“D”)的大写 D,所以我认为以某种方式访问了随机位置。
#include <stdio.h>
int main(void)
{
//Function Prototypes:
void CopyAString(const char * s1, char s2[]);
// Initialize the string literal str1 and an array s2 of size 12.
const char *str1 = "Hello World";
char s2[12];
// In the function i pass the address of str1 and the array s2.
CopyAString( &str1, s2 );
for (int i = 0; i <= 12; i++){
printf("%c", s2[i]);
}
}
void CopyAString(const char * s1, char s2[])
{
const char * p1 = s1;
int index = 0;
while (*p1 != '\0') {
s2[index] = *p1;
index++;
p1++;
}
}
【问题讨论】:
-
您忘记将 NUL 终止符
'\0'写入字符串。此外,最好按照标准库函数strcpy()的方式对参数进行排序。 -
您还使用
CopyAString( &str1, s2 );错误地调用了该函数,因为编译器会发出警告。请打开编译器警告。另外:您输出的字符太多(超出了数组范围)。 -
感谢您的评论!但是,NULL 终止符是编译器在赋值后自动放置的 const char *str1 = "Hello World";
-
不,你停在那个不复制它。
-
编译器会在
str1指向的字符串末尾放置一个NUL终止符。确实如此。但是,您负责将数据写入数组s2[]。编译器无法知道您的函数CopyAString是否故意不在那里放置 NUL 字符。在某些情况下不需要 NUL 字符...
标签: arrays c copy c-strings function-definition