指针在函数中的解引用指针(但不在main中)

时间:2017-04-10 15:38:39

标签: c pointers

我是初学者,这个问题可能听起来很愚蠢,但无论如何希望你们能帮忙。在这个程序中,我有变量char a,b是指向a的指针,我将b的地址传递给函数test。然后c是函数test中b的指针,c是变量a的指针。我的问题是:是否有任何可能的方法来取消引用c并打印出来。我不想打印出一个主函数,我想在执行测试(& b)时在功能测试中执行此操作。无论如何都要这样做。

下面是我的代码(它没有完成,因为我无法找到解除引用c以获得函数测试的方法)。先感谢您。

#include<stdio.h>
#include<string.h>

void test(char *c)
{
    // how can  i get a from test function.
}

int main(void)
{
    char a =  'a' ;
    char *b = &a;
    test(&b);
}

2 个答案:

答案 0 :(得分:1)

c包含b的地址,因此*cb相同。

b包含a的地址,因此**c*ba相同。

请注意,如果要继续传递指向char的指针,则需要将原型更改为

void test(char **c)

所有在一起:

void test(char **c)
{
    printf("%c\n", **c);  // a
    **c = 'c';
}

int main(void)
{
    char a = 'a';
    char *b = &a;
    test(&b);
    printf("%c\n", a);  // c
}

您确定需要额外的间接级别吗?

void test(char *b)
{
    printf("%c\n", *b);  // a
    *b = 'b';
}

int main(void)
{
    char a = 'a';
    test(&a);
    printf("%c\n", a);  // b
}

答案 1 :(得分:0)

您的类型不匹配。

由于achar&a将是char*,您可以将b分配给b,因为char*也是&b {1}}。到目前为止一切都很好。

但是 - 当你调用该函数时,你使用char** char*。但是,该函数需要#include<stdio.h> #include<string.h> void test(char *c) { printf("%c\n", *c); // Will print the value of a, i.e. 'a' *c = 'b'; // Will assign new value to a } int main(void) { char a = 'a' ; test(&a); printf("%c\n", a); // Will print the value of a, i.e. 'b' return 0; } ,因此您的类型不匹配。

您只需要:

class Load{

    public function __construct(){

    }

    public function view(){
        echo "Hello";
    }

    public function files(){

    }

    public function plugins(){

    }

}


$this->load->view();
相关问题