简体   繁体   English

多次分配后C指针丢失

[英]C pointer lost after multiple assignments

I am new to C programming and having some issues with the pointers in the following code. 我是C编程新手,下面的代码中的指针存在一些问题。 I am using the C89 standard. 我正在使用C89标准。

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

char * b(char *p) {

    char *z;

    z = p;

    printf("b(): %s\n", z);

    return z;

}

void a(char *p, char *q) {

     q = b(p);
     printf("a(): %s\n", q);
}

void main(void) {

    char *p = (char *) malloc(15);
    char *q;

    strcpy(p, "This is a test");

    a(p,q);

    printf("main(): %s\n", q);

    free(p);
}

For some reason, my printf function is printing nothing in the main() function. 由于某种原因,我的printf函数在main()函数中什么也不打印。 The printf calls in both of the functions a() and b() are working. 函数a()b()中的printf调用均有效。 I am not sure why my pointer "q" is lost in the main function. 我不确定为什么我的指针“ q”在主函数中丢失了。 I even tried allocation dynamic memory to "q" in main() function but still no results. 我什至尝试在main()函数中将动态内存分配给“ q”,但仍然没有结果。

q in main() is uninitialized. main() q未初始化。 You probably assume that q is changed after a(p,q) , but as that pointer is passed by value (as everything in C), after returning from a , any changes done to q are discarded (they were local to a ) 您可能假设qa(p,q)之后发生a(p,q)变化,但是由于该指针是按值传递的(就像C中的所有内容一样),从a返回后,对q所做的任何更改都将被丢弃(它们对a是局部a

To solve this, while preserving most of your function signatures, you would have to add another level of pointers 为了解决这个问题,在保留大多数函数签名的同时,您必须添加另一级指针

In following code, p and q in a are local to a , but you are not directly changing any of them, insted, you are modifying value, that is pointed at by q (that value is of type *char , so another ponter, easy to get lost) 在下面的代码中, pq对于a是局部a ,但是您并没有直接更改它们,而是在修改由q指向的值(该值是*char类型,所以是另一个ponter,容易迷路)

void a(char *p, char **q) {

     *q = b(p);
     printf("a(): %s\n", q);
}

void main(void) {
    ...
    a(p,&q);

    printf("main(): %s\n", *q);

    ....
}

Or simply return that pointer, and assign to q in main (as you have done in b ) 或者简单地返回该指针,然后将它赋给main q (就像在b所做的那样)

To better understand why this is happening, consider this simpler example: 为了更好地理解为什么会发生这种情况,请考虑以下简单示例:

void foo(int a) {
    print("value is %d\n", a);
    a = 42; // modifies only a local copy of passed parameter a
    print("modified value is %d\n", a);
}

int main() {
    int a = 0
    printf("initial value is %d\n", a);
    foo(a);
    printf("value after returning is (still) %d\n, a");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM