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

时间:2012-02-05 10:36:11

标签: c pointers

gcc 4.6.2 c89

我正在传递一个指向函数的指针。该指针将传递给另一个函数。并且取决于当前值,该值将被更改。因此,在main中,更改的值将在函数中更改值。

因为我正在经历2个功能。我只是想确保我没有做任何会导致未定义行为的事情。因为这将在具有高交易的系统上运行。

我无法返回返回类型中的值,因为我需要返回TRUE或FALSE,以查看函数是成功还是失败。

我在valgrind下运行,它没有报告错误:

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

非常感谢任何建议,

#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;
}

1 个答案:

答案 0 :(得分:1)

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