【问题标题】:How can I change the value of a char using a pointer?如何使用指针更改 char 的值?
【发布时间】:2023-04-04 18:36:01
【问题描述】:

所以我对使用指针很陌生,想知道除了字符串值之外我可以如何执行以下操作。

int number(int, int *);
int main()
{
    int a = 15;
    int b =0;
    
    number(a,&b);
    
    fprintf(stdout,"Number b is %d\n",b);
    return 0;
}


int number(int a, int *b) {
    
    *b = a;
     
}

【问题讨论】:

标签: c function pointers pass-by-reference c-strings


【解决方案1】:

你的意思好像是这样的

#include <stdio.h>

char * assign( char **s1, char *s2 )
{
    return *s1 = s2;
}

int main(void) 
{
    char *s1 = "Hello World!";
    char *s2;
    
    puts( assign( &s2, s1 ) );
    
    return 0;
}

程序输出是

Hello World!

即为函数中的指针s2(类型为char *)分配一个值,您需要通过引用将其传递给函数,就像您在程序中使用类型对象所做的那样int。否则该函数将处理其参数的副本,并且更改副本不会影响参数。

在 C 中通过引用传递对象意味着通过指向它的指针间接传递对象。

如果您有存储字符串的字符数组,那么要将字符串复制到字符数组,您可以使用标头 &lt;string.h&gt; 中声明的标准字符串函数 strcpy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多