0

I'm currently working on a c project, and I keep getting the same error when I try and run the program. There's a total of 3 files in the program, a main.c, a header.c and a header.h. Here is the complete code of the filest:

main.c

#include "header.h"
#include <stdio.h>

int main() {    
    printf("Hello");

    Person p1;
    p1.age = 15;
    p1.name = "bob";
    printPerson(p1);
}

header.h

#ifndef HEADER_H
#define HEADER_H

typedef struct person_t {
    char* name;
    int age;
} Person;

void printPerson (Person person);

#endif

header.c

#include <stdio.h>
#include "header.h"

void printPerson (Person person) {
    printf("Name: %s, age: %d", person.name, person.age);
    }

I used the "run" button in this specific example, but even when I used gcc the .exe file just got stuck when arriving at the problematic function. It looks like I'm missing something important but I can't tell what it is... any ideas?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
yoaviv
  • 1
  • 1
    Can you include the exact error message you are getting? – Andy Preston Apr 25 '23 at 11:55
  • well, are you linking header (not a great name for a compilation unit, very misleading!) with main? – Marcus Müller Apr 25 '23 at 11:55
  • So you get this error when building from the IDE, and no error when building from the command line (but no output also)? – HolyBlackCat Apr 25 '23 at 11:55
  • There is no space reserved for `name`. While this *happens* to work in your case (as you make `name` point to a literal), it will blow up as soon as you attempt to read `name` from somewhere (user input?). In C you have to `malloc` space for your strings (which are just arrays of `char`), `strcpy` them, and `free` the space if you no longer need it – DevSolar Apr 25 '23 at 11:59
  • 1
    @DevSolar OP doesn't attempt to modify `name` though. Making the pointer `const` to avoid accidental modification would be enough. – HolyBlackCat Apr 25 '23 at 12:02
  • 1
    Your code is fine (well not quite, see DevSolar's comment), but it should definitly output `HelloName: bob, age: 15`. How do you compile? – Jabberwocky Apr 25 '23 at 12:07
  • @ryyker *"unknown what the pointer name is pointing to"* What do you mean? It points to a string literal. – HolyBlackCat Apr 25 '23 at 12:38
  • @HolyBlackCat - Missed that! deleted comment. – ryyker Apr 25 '23 at 12:39

0 Answers0