2017-07-16 4 views
0

私はこのようになります構造体があります。その後、私はリストを作成するには、このメソッドを持っているC:なぜprintステートメントがstructメンバーの値を変更していますか?

typedef struct 
{ 
     int *numberList; 
     int size; 
     int maxNumber; 
} list; 

を:

list* createList(int maxNumber) 
{ 
    list l; 
    l.size = 0; 
    l.numberList = malloc(maxNumber*sizeof(int)); 
    list* ptr = &l; 
    return ptr; 
} 

その後、私は作品にこの方法があります:createListから

int updateSize(list *ls) 
{ 
    ls->size++; 
    printf("This is a print statement.\n"); 

    return 0; 
} 

I check the value of size in my main method and it works fine for both initialization and the update, but when it gets to the print statement, size changes to a large incorrect number (garbage value?), e.g. 4196190 instead of 1. In the full version of my code I also use malloc() in my updateSize() for my numberList and even that keeps the results as they should be up until the print statement. My question is: What is it about the print statement that alters the member(s) of my struct?

+0

ところで、 'l.maxNumber'は割り当てられていません。 – chux

答えて

4

You return the address of lを、しかし、 lはその関数のローカルなので、それが占めるスペースは他のもののために使用することができ(そして明らかに)、以前にあったものを上書きすることができます。

関連する問題