#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’发布于 2018-08-13 05:25:29
在main()中调用str_cat(char *, char *)不正确。如果你使用像char *p = a;这样的指针,那么*p就是一个允许你访问p引用的内存的表达式。因此,在指针上执行*p称为解引用。在这种情况下,这不是您想要的,因为str_cat需要一个指针而不是一个值。我下面的例子做了你想要的。您可以看到,声明额外的指针是不必要的。
int main()
{
char a[MAX] = "Hello, ";
char b[MAX] = "world!";
str_cat(a, b);
printf("The new string is %s.\n", a);
return 0;
}发布于 2018-08-13 10:28:24
在str_cat函数中,您应该传递str_cat(p,q)而不是str_cat(*p,*q)。并且此函数中的代码存在问题。在第一个while循环中,while循环将在*s = '\0‘时结束。并将S递增到下一个地址。因此,在下一次while循环中,指针s所指向的字符串将包含'\0‘字符。结果将如下所示:"Hello,'\0'world!“因此,在str_cat()调用之后,字符串a仍然是"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++);
}https://stackoverflow.com/questions/51812535
复制相似问题