gpt4 book ai didi

c - K&R练习5-3 : passing pointers to functions

转载 作者:行者123 更新时间:2023-11-30 19:30:00 25 4
gpt4 key购买 nike

#include <stdio.h>
#define MAX 100
void str_cat(char *s, char *t);

int main()
{
char a[MAX] = "Hello, ";
char b[MAX] = "world!";
char *p;
char *q;
p = a;
q = b;
str_cat(*p, *q);
printf("The new string is %s.\n", a);

return 0;
}

void str_cat(char *s, char *t)
{
while (*s++)
;
while (*s++ = *t++)
;
}

编译器错误:

str_cat.c: In function ‘main’:
str_cat.c:13:11: warning: passing argument 1 of ‘str_cat’ makes pointer from integer without a cast [-Wint-conversion]
str_cat(*p, *q);
^
str_cat.c:3:6: note: expected ‘char *’ but argument is of type ‘char’
void str_cat(char *s, char *t);
^~~~~~~
str_cat.c:13:15: warning: passing argument 2 of ‘str_cat’ makes pointer from integer without a cast [-Wint-conversion]
str_cat(*p, *q);
^
str_cat.c:3:6: note: expected ‘char *’ but argument is of type ‘char’

最佳答案

在 str_cat 函数中,您应该传递 str_cat(p,q) 而不是 str_cat(*p, *q)。您的该函数中的代码有问题。在第一个 while 循环中,当 *s = '\0' 时,while 循环将结束。并将 s 递增到下一个地址。因此,在下一个 while 循环中,指针 s 指向的字符串将包含 '\0' 字符。结果将是这样的:“Hello, '\0'world!”。因此,在 str_cat() 调用之后,字符串仍然是“Hello,”。此代码应该按您的预期工作:

#include <stdio.h>
#include <string.h>
#define MAX 100
void str_cat(char *s, char *t);

int main()
{
char a[MAX] = "Hello, ";
char b[MAX] = "world!";
char *p;
char *q;
p = a;
q = b;
str_cat(p, q);
printf("The new string is %s.\n", a);

return 0;
}

void str_cat(char *s, char *t)
{
while(*s)
s++;
while(*s++ = *t++);
}

关于c - K&R练习5-3 : passing pointers to functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51812535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com