【发布时间】:2014-06-18 14:19:25
【问题描述】:
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(source)而不是sizeof(destination),因为我正在移动源的字节吗?
第三,在 strncpy 之后添加空终止字符对我来说很有意义,因为我已经读过它不会自行添加空字符,但我收到警告说它可能越界从我的pelles c IDE存储。
第四个也是最重要的,为什么简单的 strcpy 不起作用?!?!
/////////////////////////////////////// /////////////////////////////////////////p>
更新:
#include <stdio.h>
#include <string.h>
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 中的字符串库。
【问题讨论】:
-
很可能,
sizeof在这里完全不合适,无论是源大小还是目标大小。 -
你能给一个complete, minimal example 而不仅仅是这个sn-p 吗?特别是,了解
second的样子会很有用。 -
sentence2[10] = '\0';超出范围,并导致未定义行为。 -
我尝试用目标字节大小(10 个字节)替换该部分,但仍然无法正常工作。我也尝试删除空字符分配,但没有任何改变。
-
@alvits 也尝试过 .. 没有任何改变。