简体   繁体   English

更改已传递给函数的指针的值

[英]Changing a value of a pointer that has been passed to a function

gcc 4.6.2 c89 gcc 4.6.2 c89

I am passing a pointer to a function. 我正在传递一个指向函数的指针。 This pointer will be passed to another function. 该指针将传递给另一个函数。 And depending on the current value, the value will be changed. 并根据当前值更改该值。 So in main the value changed will be value changed in the function. 因此,更改后的值主要是函数中的更改值。

Because I am going through 2 functions. 因为我要执行2个功能。 I just wanted to make sure I haven't done anything that would cause undefined behaviour. 我只是想确保我没有做任何会导致不确定行为的事情。 As this will run on a system with high transcations. 因为这将在具有高交易量的系统上运行。

I cannot return the value in the return type, as I need to return TRUE or FALSE so see if the function succeeded or failed. 我无法以返回类型返回值,因为我需要返回TRUE或FALSE,因此请查看函数成功还是失败。

I have run under valgrind and it reports no errors: 我已经在valgrind下运行,它没有报告错误:

valgrind --leak-check=full --verbose ./ptr

Many thanks for any suggestions, 非常感谢您的任何建议,

#include <stdio.h>

#define FALSE 0
#define TRUE (!FALSE)

static int incoming_sdp(int *pcmu_priority);
static int parse_incoming_sdp(int *pcmu_priority);

int main(void)
{
    int pcmu_priority = 10;

    printf("Start program pcmu_priority [ %d ]\n", pcmu_priority);

    if(incoming_sdp(&pcmu_priority) == FALSE) {
        /* Something bad happened */
    }

    printf("Final pcmu priority [ %d ]\n", pcmu_priority);

    return 0;
}

/* Removed the processing that will determine of the function is success of failure */
static int incoming_sdp(int *pcmu_priority)
{
    /* Pass the value of the pcmu_prority */
    if(parse_incoming_sdp(pcmu_priority) == FALSE) {
        return FALSE;
    }

    /* Return true or false if processing was successfull */
    return TRUE;
}

/* Removed the processing that will determine of the function is success of failure */
static int parse_incoming_sdp(int *pcmu_priority)
{
    /* Now change the value of the pcum_priority */
    if(*pcmu_priority == 10) {
        *pcmu_priority = 20;
        printf("pcmu is 10 changing pcmu_priority to [ %d ]\n", *pcmu_priority);
    }
    else if(*pcmu_priority == 20) {
        *pcmu_priority = 10;
        printf("pcmu is 20 changing pcmu_priority to [ %d ]\n", *pcmu_priority);
    }

    /* Return true or false if processing was successfull */
    return TRUE;
}

该程序很好,并且不会产生依赖于未定义行为的输出。

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

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