wokoro douye samuel
wokoro douye samuel

Reputation: 2374

how to print variable in c struct

Please am finding it difficult to print variable b in my struct declaration

sum.h
#ifndef SUM_H_
#define SUM_H_

typedef struct sumTAG{
  int a;
  int b;    
}Sum;

void addition();
void initialize();

#endif

sumtest.c

#include "../headers/sum.h"
#include <stdio.h>

void initialize(Sum *S){
  S->a = 10;
  S->b = 10;
}

void addition(Sum* s){

  printf("the value of a is : ", s->a);

}

int main(){

  Sum *sum;
  initialize(sum);
  addition(sum);

  return 0;
}

I keep getting a runtime error with return value of 225;

Upvotes: 1

Views: 86

Answers (1)

areller
areller

Reputation: 5238

Sum *sum;

is a pointer to nowhere, until you set it to point to something. It could point to an allocated memory:

Sum *sum = malloc(sizeof(Sum));

Which is probably what you want to do in your case. But it could also point to a local variable,

Sum sum;
Sum *pointerToSum = &sum;
initialize(pointerToSum);
addition(pointerToSum);

The error you get is probably due to trying to dereference a null pointer.

Upvotes: 3

Related Questions