#include
#include
#include
#include
# include "ctype. H"
#include
Typedef struct t1 {
int val;
} TT;
Typedef struct t2 {
TT * va;
} qq;
{int cl * w (qq)
TT * TMP;
TMP=w - & gt; The va.
Printf (" tmp1=% d \ n ", TMP [0]. Val);
TMP [0]. Val=2;
Printf (" tmp2=% d \ n ", TMP [0]. Val);
return 0;
}
Int main () {
Qq * w;
Int len=sizeof (qq) + 5 * sizeof (TT);
Printf (" 1 ");
W=* (qq) malloc (len);
//memset (w, 0 x00, len);
Printf (" 2 ");
W - & gt; Va [0]. Val=5;
Printf (" 3 ");
Printf (" w1=% d \ n ", w - & gt; Va [0]. Val);
Printf (" 4 ");
Cl (w);
Printf (" w2=% d \ n ", w - & gt; Va [0]. Val);
return 0;
}
The memset plus, can print out the 12. Remove the memset, can print 123.
Why is this?
This assignment have what problem? Value of print and where is wrong?
CodePudding user response:
You have the wrong codeTypedef struct t2 {
TT * va;
} qq;
Qq * w
Your w initialization, but w va uninitialized, is undefined behavior to his visit,
CodePudding user response:
Allocated memory is wrong, change to the following, compare the difference betweenW=* (qq) malloc (sizeof (qq));
W - & gt; Va=(*) TT malloc (5 * sizeof (TT));
W=* (qq) malloc (len);//here although allocated more memory, but for w - & gt; Is still not allocate memory va, w - & gt; Va or wild pointer
Memset plus, will cause w - & gt; The va memory information is 0, that is, w - & gt; Va to NULL, so w - & gt; Va [0]. Val=5; Will quote null pointer errors, that is, only print 12
If you don't add memset, w - & gt; Va memory information is random (i.e., wild pointer), w - & gt; Va [0]. Val=5; The wild pointer (that is, the illegal memory address) write data, will cause unpredictable errors, so this may print out 123, the next may print out 1234 (that is, the result is random), but the program is illegal access to other memory, after all complains sooner or later,
CodePudding user response:
What is the difference between this and flexible array? https://blog.csdn.net/tjw316248269/article/details/104791911 as array [], also is not equivalent to a pointer?CodePudding user response: