-7

I have 3 files

a.h:

Struct a{ int I;}

b.c:

#include "a.h"
Main(){
    Struct a *b= hello();
}

C.c:

#include"a.h"
Struct a *hello(){
    Struct a *c= malloc (size of *(*c));
    c->I = 100;
    Return c;
}

And compiling .H file first ,then c.c file then b.c file,so here when main calls hello() function and it is returning c value address is correct while I am assigning to b,it is giving wrong address ,for example c value is 0x10322345 then b is 0xffff345 like this.....

ikegami
  • 367,544
  • 15
  • 269
  • 518

1 Answers1

1

First of all, always turn on your compiler's warnings! With gcc, this is done by passing

-Wall -Wextra -pedantic

Although, oddly enough, the warning in question is on by default in gcc, so you should have seen something like

main.c: In function ‘main’:
main.c:6:14: warning: initialization makes pointer from integer without a cast [enabled by default]

If you don't understand a warning, don't ignore it! Ask about it instead.


You called hello without declaring it, so it was implicitly declared as int hello();

a.h:

typedef struct { int i; } a_t;

a_t* hello(void);

a.c:

#include <stdlib.h>
#include "a.h"

a_t* hello(void) {
    a_t* a = malloc(sizeof(a_t));
    a->i = 100;
    return a;
}

main.c:

#include <stdio.h>
#include <stdlib.h>
#include "a.h"

int main(void) {
    a_t* a = hello();
    printf("%d\n", a->i);
    free(a);
    return 0;
}

Output:

$ gcc -Wall -Wextra -pedantic -o main main.c a.c && main
100
ikegami
  • 367,544
  • 15
  • 269
  • 518