首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >K&R练习5-3:传递指向函数的指针

K&R练习5-3:传递指向函数的指针
EN

Stack Overflow用户
提问于 2018-08-13 04:22:54
回答 2查看 158关注 0票数 -1
代码语言:javascript
复制
#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++)
        ;
}

编译器错误:

代码语言:javascript
复制
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’
EN

回答 2

Stack Overflow用户

发布于 2018-08-13 05:25:29

main()中调用str_cat(char *, char *)不正确。如果你使用像char *p = a;这样的指针,那么*p就是一个允许你访问p引用的内存的表达式。因此,在指针上执行*p称为解引用。在这种情况下,这不是您想要的,因为str_cat需要一个指针而不是一个值。我下面的例子做了你想要的。您可以看到,声明额外的指针是不必要的。

代码语言:javascript
复制
int main()
{
    char a[MAX] = "Hello, ";
    char b[MAX] = "world!";
    str_cat(a, b);
    printf("The new string is %s.\n", a);

    return 0;
}
票数 0
EN

Stack Overflow用户

发布于 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,“。这段代码应该能像您预期的那样工作:

代码语言:javascript
复制
#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++);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51812535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档