K&R练习5-3:将指针传递给函数

时间:2018-08-12 20:22:54

标签: c pointers

#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’

2 个答案:

答案 0 :(得分:0)

str_cat(char *, char *)中对main()的呼叫是错误的。如果采用类似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;
}

答案 1 :(得分:0)

在str_cat函数中,您应该传递str_cat(p,q)而不是str_cat(* p,* q)。 并且此函数中的代码存在问题。在第一个while循环中,当* s ='\ 0'时,while循环将结束。并将s递增到下一个地址。因此,在下一个while循环中,指针s指向的字符串将包含'\ 0'字符。结果将如下所示:“您好,'\ 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++);
}