c - Pointers to structures, fields changing values inexplicably -


I am ready to complete that I am doing something stupid / wrong; This is what I expect.

I feel a feeling for the structures and the crop is coming from the fields to reach the fields. Follow the code.

Matrix. H:

  #ifndef MATRIX_H_INCLUDED #define MATRIX_H_INCLUDED #include & lt; Stdlib.h & gt; Typefif structure {size_t size; Int * vector; } Vector_t; #endif // MATRIX_H_INCLUDED   

main.c:

  #include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; #include "Matrix." Vector_t * vector_new (size_t size) {int vector [size]; Vector_t v; V.size = Size; V.vector = vector; Return & amp; V } Int main (int argc, char * argv []) {vector_t * vec = vector_new (3); Printf ("v size is% d. \ N", vec-> size); Printf ("v is size% d. \ N", vec-> size); Return EXIT_SUCCESS; }   

So this is a very simple program where I am creating a vector structure of size 3, return the pointer to the structure and print its size. This is the first print frequency at 3 which then changes to the next print at 2686668. What is happening?

Thanks in advance.

You are returning an indicator from the local variable v to The vector_new does not have a small chance to do this work till all the local variables are destroyed by the time of returning to vector_new and on main and Your pointer does not go anywhere. In addition, the memory v.vector is also a local array vector . It also gets destroyed when vector_new returns.

This is the reason why you see garbage printed by your printf .

Your code should be completely replaced with respect to memory management. The actual code should be allocated dynamically using the malloc vector_t object can be dynamically allocated or in the main Can be declared as a local variable and it has been passed to vector_new to get started (depending on which method you want to follow depends on you).

For example, if we decide to do everything using dynamic allocation, then it can be of the following type

  vector_t * vector_new (size_ size) ) {vector_t * v = malloc (sizeof * v); V- & gt; Size = size; v-> gt; Vector = malloc (v- & gt; size * size * v- & gt; vector); Return V; }   

(And do not forget to check that malloc is successful).

However, we have been dynamically allocated, using free later. Therefore, you have to write a vector_free function for that purpose.

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -