-1

I am usiung MinGW as my c programing environment, but I found a serious problem. My test code is as follows:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct {        /* time struct */
    time_t time;        /* time (s) expressed by standard time_t */
    double sec;         /* fraction of second under 1 s */
} gtime_t;

typedef struct {       
    gtime_t time;        
    int type;         
} raw_t;

int main(){
    raw_t *t;
    gtime_t t0={0};
    t->time = t0;
    printf ("%d",(t->time).time);

    return 0;
}

I defined two struct and one struct is contained in the other one. When I run this test program, it will crush on line

t->time = t0;

Can someone help me on this?

M.M
  • 138,810
  • 21
  • 208
  • 365
CPPCC
  • 26
  • 1
  • when copying a struct, a simple assignment will (usually) not do the job. Suggest: `memcpy( &t->time, &to, sizeof( gtime_t ) ); – user3629249 Oct 15 '15 at 05:34
  • the `double` format has an offset in the exponent, so initializing to {0} will not result in a value that is 0.0. Suggest reading" which contains: "The double-precision binary floating-point exponent is encoded using an offset-binary representation, with the zero offset being 1023; also known as exponent bias in the IEEE 754 standard" – user3629249 Oct 15 '15 at 05:45

2 Answers2

3

t is a pointer that has not been initialized. So you can't dereferenced it to assign value to member. You can either initialize it by heap

t = malloc(sizeof(raw_t));

Or initialize by stack

raw_t tonthestack;
raw_t *t = &tonthestack;
Phuong Nguyen
  • 909
  • 7
  • 20
1

Your code uses an uninitalized pointer:

raw_t *t;
t->time = 

You must make t point somewhere before you are allowed to write t->.

A simpler solution would be to not use a pointer at all:

raw_t t = { 0 };
printf("%d\n", t.time.time);
M.M
  • 138,810
  • 21
  • 208
  • 365