我正在尝试为学校作业实施这些功能。我知道我的程序的逻辑是什么,但它的表现有点奇怪。我将在这里感谢一些帮助
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
char *StrCat (char *destination, const char* source) {
destination = malloc(sizeof(source) + sizeof(destination));
char *temp = destination;
while (*temp != '\0') {
printf("temp: %c - ", *temp);
temp++;
}
int i;
for (i = 0; source[i] != 0; i++) {
*temp = source[i];
}
temp[i++] = 0;
return destination;
}
char *StrCpy(char *destination, const char* source) {
destination = malloc(sizeof(source) * sizeof(char));
int i;
for (i = 0; source[i] != '\0'; i++) {
destination[i] = source[i];
}
destination[i++] = '\0';
return destination;
}
int main ()
{
char *src;
char *dest;
src = StrCpy(src, "A source sentence");
dest = StrCpy(dest, "This is the destination sentence");
printf("%s\n%s\n", src, dest);
StrCat(dest, src);
printf("Final destination string : |%s|", dest);
return(0);
}
这是输出
A source sen
This is the destination sentence
temp: i - temp: n - temp: a - temp: t - temp: i - temp: o - temp: n - temp: - temp: s - temp: e - temp: n - temp: t - temp: Q - temp: e - temp: s - temp: t - Final destination string : |This is the |
另外,当我注释掉
时dest = StrCpy(dest, "This is the destination sentence");
行,我得到了这个输出
A source sentence
(null)
temp: e - Final destination string : |(null)|
我的问题是:当我没有在dest上调用StrCpy时,为什么src打印正确?另外,在第一个输出中,为什么temp应该从字母i开始,当它应该指向目标的第一个元素时?
谢谢
答案 0 :(得分:0)
您需要小心使用sizeof()
。
在以下情况下,sizeof()
将返回系统上指针的大小(可能是4/8字节),而不是char
的大小,或者字符串的长度(这就是您使用它的方式)。
char *myString;
printf("sizeof(myString): %d\n", sizeof(myString));
您实际需要的是指针所指向的类型的大小...为此,您需要将指针“取消引用”一次。这将为您提供单个char
的大小。
char *myString;
printf("sizeof(myString): %d\n", sizeof(*myString));
要获取字符串的长度,您需要使用strlen()
:
char myString[] = "Testing 123...";
printf("string length: %d\n", strlen(myString));
接下来,你需要检查一下你对strcpy()
的理解......
标准strcpy(3)
将期望source
和destination
都是现有缓冲区。它还期望目标具有足够的存储空间来容纳整个源,以及一个nul终结符('\0'
)。
如果不是这样,那么您的应用程序可能(希望会)因分段错误而崩溃,或者覆盖其他变量。
这是strcpy()
在行业中经常被不赞成使用的原因之一 - 更喜欢使用strncpy()
。
strncpy()
函数类似,只是复制了最多n个字节的src。 警告:如果src的前n个字节中没有空字节,则放在dest中的字符串将不会以空值终止。
我希望看到你使用以下原型实现函数,如果你的导师抱怨,那么你的任务的扩展就是理解为什么n
参数很重要,并向他们解释。
/* append the 'source' to the 'destination', allowing the total length of 'destination' to
* be no longer than 'n' bytes, including the terminating nul */
char *StrnCat (char *destination, const char* source, size_t n);
/* copy the 'source' to the 'destination', allowing the total length of 'destination' to
* be no longer than 'n' bytes, including the terminating nul */
char *StrnCpy(char *destination, const char* source, size_t n);
如果您在main()
函数中为字符串分配存储空间,则根本不必担心malloc()
。
这是一个学习机会,所以我不打算为你实施。