This question already has answers here:
Returning an array using C
                                
                                    (8个答案)
                                
                        
                                在11个月前关闭。
            
                    
我试图了解C的行为,发现了一些奇怪的东西。
我进行了调试,发现表值在调用printf之前是正确的。
我创建了一个void函数来测试它是否是范围问题,但是在调用此函数后,表值仍然保持正确。
我现在想知道printf是否删除以前的局部变量。

#include <stdio.h>
#include <stdlib.h>
void invertTable(int** tableau,int size){
    int temp[size];
    for(int i = 0; i < size; i++)
    {
        temp[i]=-1*tableau[0][i];
    }
    tableau[0]=temp;
}
void test(){

}
int main(int argc, char const *argv[])
{
    int* table=(int*)malloc(5*sizeof(int));
    table[0]=1;
    table[1]=2;
    table[2]=3;
    table[3]=4;
    table[4]=5;
    invertTable(&table,5);
    test();
    for(int i = 0; i < 5; i++)
    {
        //Here is the problem
        printf("\n %d \n",table[i]);
    }
    free(table);
    return 0;
}


预期-1 -2 -3 -4 -5

输出:-1 1962295758 1 1962550824 1962295741

最佳答案

为了获得正确的输出,您应该更改

int temp[size]int* temp = *tableauint* temp = (int*) malloc(sizeof(**tableau) * size)

这些解决方案之所以有效,是因为*tableau和/或malloc分配的内存在invertTable之后没有被破坏。

通常,应在temp函数之后将invertTable销毁,并使tableau[0]成为悬空指针,然后系统可以重新分配temp指向的内存。因此,这部分内存现在可能包含随机数据。这些数据可能是您在执行时获得的。

10-08 11:03
查看更多