Initializing a struct and assigning it's parameters within a function The Next CEO of Stack OverflowHow do you pass a function as a parameter in C?How to initialize a struct in accordance with C programming language standardsAnonymous union within struct not in c99?Basic question: C function to return pointer to malloc'ed structString Element of Struct not retaining assigned valueDo you need to malloc space for function pointers in a struct in C?Using a function to alter typedef fields when individual structs are identified using an arrayPassing in a struct to a function and assigning itSpecify struct size for unique_ptr during initializationStruct becomes NULL even after assigning value from another function in a loop

Audio Conversion With ADS1243

Aggressive Under-Indexing and no data for missing index

Do scriptures give a method to recognize a truly self-realized person/jivanmukta?

What CSS properties can the br tag have?

What is the process for cleansing a very negative action

Players Circumventing the limitations of Wish

Why do we say 'Un seul M' and not 'Une seule M' even though M is a "consonne"

Can you teleport closer to a creature you are Frightened of?

Calculate the Mean mean of two numbers

free fall ellipse or parabola?

Does destroying a Lich's phylactery destroy the soul within it?

Decide between Polyglossia and Babel for LuaLaTeX in 2019

Can someone explain this formula for calculating Manhattan distance?

Lucky Feat: How can "more than one creature spend a luck point to influence the outcome of a roll"?

It is correct to match light sources with the same color temperature?

Is there an equivalent of cd - for cp or mv

Expressing the idea of having a very busy time

Why did early computer designers eschew integers?

What happened in Rome, when the western empire "fell"?

What was Carter Burke's job for "the company" in Aliens?

Do I need to write [sic] when including a quotation with a number less than 10 that isn't written out?

Man transported from Alternate World into ours by a Neutrino Detector

Is there a difference between "Fahrstuhl" and "Aufzug"?

Can I board the first leg of the flight without having final country's visa?



Initializing a struct and assigning it's parameters within a function



The Next CEO of Stack OverflowHow do you pass a function as a parameter in C?How to initialize a struct in accordance with C programming language standardsAnonymous union within struct not in c99?Basic question: C function to return pointer to malloc'ed structString Element of Struct not retaining assigned valueDo you need to malloc space for function pointers in a struct in C?Using a function to alter typedef fields when individual structs are identified using an arrayPassing in a struct to a function and assigning itSpecify struct size for unique_ptr during initializationStruct becomes NULL even after assigning value from another function in a loop










0















I have done some searching around and can't seem to find an exact answer to my question. It seems like it should work but it doesn't. Here's my code:



typedef struct stack_strut 
Item* top;
int size;
stack;

void initialize(stack* s)
s = (stack*)malloc(sizeof(stack));
s->size = 0;


int main()
stack s;
initialize(&s);
return 0;



That's a condensed version obviously. I was under the impression that I'd be able to modify the contents of the struct since I'm passing a pointer to it, so a change a make inside the function should stick around after it returns. If I use a print statement inside the initialize function to check the size, it successfully prints 0. However, If I use another print statement in main immediately after initialize returns, the size of s is now a very large number. Is it because I didn't initialize s outside the function? I have to keep it in this format because the main function supplied by my professor starts off in the same way:



stack s;
initialize(&s);









share|improve this question






















  • Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

    – czscout
    Mar 7 at 18:40















0















I have done some searching around and can't seem to find an exact answer to my question. It seems like it should work but it doesn't. Here's my code:



typedef struct stack_strut 
Item* top;
int size;
stack;

void initialize(stack* s)
s = (stack*)malloc(sizeof(stack));
s->size = 0;


int main()
stack s;
initialize(&s);
return 0;



That's a condensed version obviously. I was under the impression that I'd be able to modify the contents of the struct since I'm passing a pointer to it, so a change a make inside the function should stick around after it returns. If I use a print statement inside the initialize function to check the size, it successfully prints 0. However, If I use another print statement in main immediately after initialize returns, the size of s is now a very large number. Is it because I didn't initialize s outside the function? I have to keep it in this format because the main function supplied by my professor starts off in the same way:



stack s;
initialize(&s);









share|improve this question






















  • Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

    – czscout
    Mar 7 at 18:40













0












0








0








I have done some searching around and can't seem to find an exact answer to my question. It seems like it should work but it doesn't. Here's my code:



typedef struct stack_strut 
Item* top;
int size;
stack;

void initialize(stack* s)
s = (stack*)malloc(sizeof(stack));
s->size = 0;


int main()
stack s;
initialize(&s);
return 0;



That's a condensed version obviously. I was under the impression that I'd be able to modify the contents of the struct since I'm passing a pointer to it, so a change a make inside the function should stick around after it returns. If I use a print statement inside the initialize function to check the size, it successfully prints 0. However, If I use another print statement in main immediately after initialize returns, the size of s is now a very large number. Is it because I didn't initialize s outside the function? I have to keep it in this format because the main function supplied by my professor starts off in the same way:



stack s;
initialize(&s);









share|improve this question














I have done some searching around and can't seem to find an exact answer to my question. It seems like it should work but it doesn't. Here's my code:



typedef struct stack_strut 
Item* top;
int size;
stack;

void initialize(stack* s)
s = (stack*)malloc(sizeof(stack));
s->size = 0;


int main()
stack s;
initialize(&s);
return 0;



That's a condensed version obviously. I was under the impression that I'd be able to modify the contents of the struct since I'm passing a pointer to it, so a change a make inside the function should stick around after it returns. If I use a print statement inside the initialize function to check the size, it successfully prints 0. However, If I use another print statement in main immediately after initialize returns, the size of s is now a very large number. Is it because I didn't initialize s outside the function? I have to keep it in this format because the main function supplied by my professor starts off in the same way:



stack s;
initialize(&s);






pointers struct






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 18:13









czscoutczscout

31




31












  • Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

    – czscout
    Mar 7 at 18:40

















  • Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

    – czscout
    Mar 7 at 18:40
















Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

– czscout
Mar 7 at 18:40





Ok, so I actually took out the first line in my initialize function, where I set space on the heap for the s struct. It works now. But I still don't full understand why? Is it because I declared s in the main function so it already had space set aside in the stack?

– czscout
Mar 7 at 18:40












1 Answer
1






active

oldest

votes


















0














The issue is when you write s = (struct*)malloc(sizeof(strucy)); it overwrites the pointer to s and you do not initialize the "good" object. You created an other one and initialized it (memory is leaked). You can check by printing the value of



The malloc is not needed the s stack is already allocated in main



#include <iostream>

struct Item
int nodeId;
;

struct stack
Item* top;
int size;
;

void initialize(stack *s)

std::cout << "initialize 1. stack at " << s << std::endl;
s = (stack*)malloc (sizeof(stack));
std::cout << "initialize 2. stack at " << s << std::endl;
s->size = 0;



int main()
stack s;
std::cout << "main 1. stack at " << &s << std::endl;
initialize(&s);
std::cout << "main 2. stack at " << &s << std::endl;
return 0;



will output (see initialize 2.)



main 1. stack at 0x7ffca7c72520
initialize 1. stack at 0x7ffca7c72520
initialize 2. stack at 0x5566830b0280
main 2. stack at 0x7ffca7c72520





share|improve this answer























  • Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

    – czscout
    Mar 7 at 18:44











  • The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

    – Nico238
    Mar 7 at 19:44











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050320%2finitializing-a-struct-and-assigning-its-parameters-within-a-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














The issue is when you write s = (struct*)malloc(sizeof(strucy)); it overwrites the pointer to s and you do not initialize the "good" object. You created an other one and initialized it (memory is leaked). You can check by printing the value of



The malloc is not needed the s stack is already allocated in main



#include <iostream>

struct Item
int nodeId;
;

struct stack
Item* top;
int size;
;

void initialize(stack *s)

std::cout << "initialize 1. stack at " << s << std::endl;
s = (stack*)malloc (sizeof(stack));
std::cout << "initialize 2. stack at " << s << std::endl;
s->size = 0;



int main()
stack s;
std::cout << "main 1. stack at " << &s << std::endl;
initialize(&s);
std::cout << "main 2. stack at " << &s << std::endl;
return 0;



will output (see initialize 2.)



main 1. stack at 0x7ffca7c72520
initialize 1. stack at 0x7ffca7c72520
initialize 2. stack at 0x5566830b0280
main 2. stack at 0x7ffca7c72520





share|improve this answer























  • Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

    – czscout
    Mar 7 at 18:44











  • The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

    – Nico238
    Mar 7 at 19:44















0














The issue is when you write s = (struct*)malloc(sizeof(strucy)); it overwrites the pointer to s and you do not initialize the "good" object. You created an other one and initialized it (memory is leaked). You can check by printing the value of



The malloc is not needed the s stack is already allocated in main



#include <iostream>

struct Item
int nodeId;
;

struct stack
Item* top;
int size;
;

void initialize(stack *s)

std::cout << "initialize 1. stack at " << s << std::endl;
s = (stack*)malloc (sizeof(stack));
std::cout << "initialize 2. stack at " << s << std::endl;
s->size = 0;



int main()
stack s;
std::cout << "main 1. stack at " << &s << std::endl;
initialize(&s);
std::cout << "main 2. stack at " << &s << std::endl;
return 0;



will output (see initialize 2.)



main 1. stack at 0x7ffca7c72520
initialize 1. stack at 0x7ffca7c72520
initialize 2. stack at 0x5566830b0280
main 2. stack at 0x7ffca7c72520





share|improve this answer























  • Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

    – czscout
    Mar 7 at 18:44











  • The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

    – Nico238
    Mar 7 at 19:44













0












0








0







The issue is when you write s = (struct*)malloc(sizeof(strucy)); it overwrites the pointer to s and you do not initialize the "good" object. You created an other one and initialized it (memory is leaked). You can check by printing the value of



The malloc is not needed the s stack is already allocated in main



#include <iostream>

struct Item
int nodeId;
;

struct stack
Item* top;
int size;
;

void initialize(stack *s)

std::cout << "initialize 1. stack at " << s << std::endl;
s = (stack*)malloc (sizeof(stack));
std::cout << "initialize 2. stack at " << s << std::endl;
s->size = 0;



int main()
stack s;
std::cout << "main 1. stack at " << &s << std::endl;
initialize(&s);
std::cout << "main 2. stack at " << &s << std::endl;
return 0;



will output (see initialize 2.)



main 1. stack at 0x7ffca7c72520
initialize 1. stack at 0x7ffca7c72520
initialize 2. stack at 0x5566830b0280
main 2. stack at 0x7ffca7c72520





share|improve this answer













The issue is when you write s = (struct*)malloc(sizeof(strucy)); it overwrites the pointer to s and you do not initialize the "good" object. You created an other one and initialized it (memory is leaked). You can check by printing the value of



The malloc is not needed the s stack is already allocated in main



#include <iostream>

struct Item
int nodeId;
;

struct stack
Item* top;
int size;
;

void initialize(stack *s)

std::cout << "initialize 1. stack at " << s << std::endl;
s = (stack*)malloc (sizeof(stack));
std::cout << "initialize 2. stack at " << s << std::endl;
s->size = 0;



int main()
stack s;
std::cout << "main 1. stack at " << &s << std::endl;
initialize(&s);
std::cout << "main 2. stack at " << &s << std::endl;
return 0;



will output (see initialize 2.)



main 1. stack at 0x7ffca7c72520
initialize 1. stack at 0x7ffca7c72520
initialize 2. stack at 0x5566830b0280
main 2. stack at 0x7ffca7c72520






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 7 at 18:34









Nico238Nico238

12128




12128












  • Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

    – czscout
    Mar 7 at 18:44











  • The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

    – Nico238
    Mar 7 at 19:44

















  • Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

    – czscout
    Mar 7 at 18:44











  • The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

    – Nico238
    Mar 7 at 19:44
















Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

– czscout
Mar 7 at 18:44





Thank you, I actually figured it out before I saw your comment, but you did confirm my suspicion as to why it didn't work. Just to confirm, I didn't need the malloc because the s struct already had space reserved for it on the stack, so overwriting it with a location in the heap means that the main function doesn't know that, and still looks for it in the stack?

– czscout
Mar 7 at 18:44













The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

– Nico238
Mar 7 at 19:44





The main fonction does not know what happens in the initialize function. Also remeberer that the s in the main is an stack object while the s parameter of initialize is a pointer to a stack (an integer).

– Nico238
Mar 7 at 19:44



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050320%2finitializing-a-struct-and-assigning-its-parameters-within-a-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved