简体   繁体   English

C新手Malloc问题

[英]C newbie malloc question

Why doesn't this print 5 ? 为什么不打印此图5

void writeValue(int* value) {
    value = malloc(sizeof(int));
    *value = 5;
}


int main(int argc, char * argv) {
    int* value = NULL;
    writeValue(value);
    printf("value = %d\n", *value); // error trying to access 0x00000000
}

and how can I modify this so it would work while still using a pointer as an argument to writeValue ? 以及如何修改它,使其在仍将指针用作writeValue的参数的情况下仍能正常工作?

Your pointer ( int *value ) is a value. 您的指针( int *value )是一个值。 If you want to keep the above behavior, you need a pointer to a pointer. 如果要保持上述行为,则需要一个指针。

void writeValue(int** value) {
    *value = malloc(sizeof(int));
    **value = 5;
}


int main(int argc, char * argv) {
    int *value = NULL;
    writeValue(&value); // Address of the pointer value, creates int**
    printf("value = %d\n", *value); // prints 5
}

There are 2 bugs, from what I see: 1) If you want to change the value of your pointer you need to pass a pointer to the pointer to your function int **value. 从我看来,有2个错误:1)如果要更改指针的值,则需要将指针传递给函数int ** value的指针。 2) If you want to print the value of the pointer in your main, you need to defreference it, *value. 2)如果要在主机中打印指针的值,则需要取消引用* value。

call malloc before calling writevalue, not inside it (thus you'll get the added benefit to be able to free it). 在调用writevalue之前而不是在内部调用malloc(这样您将获得额外的好处,可以释放它)。

Your program doesn't print 5, but also has a memory leak by losing address of allocated bloc. 您的程序不会打印5,但是还会丢失分配的块的地址,从而导致内存泄漏。

The reason as also explained by others is that the parameter int * value is a copy of int * value in main. 其他人也解释的原因是,参数int * value是main中int * value的副本。 You can think of it as a local variable of the function. 您可以将其视为函数的局部变量。 You can only access to the place it is pointing to. 您只能访问它所指向的位置。 When you modify value in the function the other value in main is not changed. 在功能中修改值时,main中的其他值不变。

void writeValue(int* value) {
    *value = 5;
}


int main(int argc, char * argv) {
    int* value = NULL;
    value = malloc(sizeof(int));
    writeValue(value);
    printf("value = %d\n", *value);
    free(value);
}

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

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