代码语言:javascript运行复制 char sentence2[10];
strncpy(sentence2, second, sizeof(sentence2)); //shouldn't I specify the sizeof(source) instead of sizeof(destination)?
sentence2[10] = '\0'; //Is this okay since strncpy does not provide the null character.
puts(sentence2);
//////////////////////////////////////////////////////////////
char *pointer = first;
for(int i =0; i < 500; i++) //Why does it crashes without this meaningless loop?!
{
printf("%c", *pointer);
if(*pointer == '\n')
putchar('\n');
pointer++;
}这就是问题所在。当我运行这段代码的第一部分时,程序崩溃。然而,当我添加for循环,只打印内存位置中的垃圾值时,它不会崩溃,但仍然不会正确地strcpy。
其次,当使用strncpy时,我不应该指定sizeof(源)而不是sizeof(目标),因为我正在移动源的字节吗?
第三,在strncpy之后添加null终止字符对我来说是有意义的,因为我读到它不会自己添加null字符,但是我从pelle c IDE中得到了一个警告,它可能超出了边界存储。
第四,也是最重要的,为什么简单的strcpy不起作用?!?!
////////////////////////////////////////////////////////////////////////////////////
更新:
代码语言:javascript运行复制#include
#include
void main3(void)
{
puts("\n\n-----main3 reporting for duty!------\n");
char *first = "Metal Gear";
char *second = "Suikoden";
printf("strcmp(first, first) = %d\n", strcmp(first, first)); //returns 0 when both strings are identical.
printf("strcmp(first, second) = %d\n", strcmp(first, second)); //returns a negative when the first differenet char is less in first string. (M=77 S=83)
printf("strcmp(second, first) = %d\n", strcmp(second, first)); //returns a positive when the first different char is greater in first string.(M=77 S=83)
char sentence1[10];
strcpy(sentence1, first);
puts(sentence1);
char sentence2[10];
strncpy(sentence2, second, 10); //shouldn't I specify the sizeof(source) instead of sizeof(destination).
sentence2[9] = '\0'; //Is this okay since strncpy does not provide the null character.
puts(sentence2);
char *pointer = first;
for(int i =0; i < 500; i++) //Why does it crashes without this nonsensical loop?!
{
printf("%c", *pointer);
if(*pointer == '\n')
putchar('\n');
pointer++;
}
}这就是我自学编程的方法。我编写代码并对我所知道的所有内容进行注释,以便下次需要查找某些内容时,只需在文件中查看自己的代码即可。在本文中,我将尝试学习c语言中的字符串库。