简体   繁体   中英

Print struct that was passed as argument in function

i have a C program, which takes an array as input which will be saves as 3 different arrays. For example:

0 2 0  
1 0 0  
0 0 3  

will be saved as Elemenets = [2,1,3] and the coordinates of the coresponding values, Rows = [1,2,3] Columns = [2,1,3] in a struct i create.

The input goes like this:

First i give the dimensions of the array, then the number of nonzero values the array has,then the values with their coordinates.

After i give the input i try to print the array with the function print2d(struct arrayCollection the array) but the array of the struct seems to have wrong numbers inside(memory addresses?). I think i am doing something wrong with the struct when i pass it as an argument to the function but i can't find the problem. I also tried to pass the struct by reference as a pointer but i had the same results.

Here is my program

My ide is xcode and the compiler is apple llvm compiler 4.1

Your struct just has pointers and not actual arrays. You are making these pointers point to local arrays, and when the function returns, those local arrays no longer exist, so your pointers point to something invalid. Trying to access data through these pointers is undefined behavior.

An alternative would be to dynamically allocate memory for your data using malloc, and have your struct's pointers point to the dynamically allocated memory instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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