0

I am about a week into my C journey so please bear with me if this is a very silly question. I've done a basic course in C but have come up to pointers, so I am trying to write a little something that will help me understand. I have the following struct defined:

typedef struct { char room_ID; char room_exits[4]; char room_description[255]; } Room; 

I am then initialising this as a player_room variable

int main(){ Room *player_Room = (Room*)malloc(sizeof(Room)); player_Room->room_ID = '0'; strcpy(player_Room->room_description, "There is an ogre in the room"); strcpy(player_Room->room_exits, "N..."); printf("%s ", player_Room->room_ID); printf(" %s", player_Room->room_description); return 0; } 

A segmentation fault occurs when debugging the code on the first printf() line above. I understand this is something of an access violation (I used to be a Delphi developer so I am used to those) trying to access memory to which my program has no access, or so I believe. It all compiles ok, just errors on that line

Once again, apologies if I am doing something stupid (I probably am) but I am very much a beginner just playing around with code trying to understand. Thanks in advance!

This is the first version of everything I have tried that has actually compiled, so I am a bit clueless as to where to go from here

9
  • 2
    Review strcpy(player_Room->room_exits, "N...");. Trying to put a size 5 string into a size 4 array. Commented Nov 2, 2023 at 22:56
  • 2
    Why should I always enable compiler warnings?. GCC emits warnings for the problem here. Commented Nov 2, 2023 at 22:57
  • printf("%s ", player_Room->room_ID); but you have char room_ID;. You should use "%c " Commented Nov 2, 2023 at 22:58
  • 2
    Thank you all for the responses, I had forgotten about null terminated strings of course (the array is now 5) and altering my printf() to use %c instead of %s (which it should be of course as its a single char) has cleared the problem! Very many thanks to all of you for your replies (I will also enable compiler warnings thank you). Very much appreciated! Commented Nov 2, 2023 at 23:03
  • 1
    Thank you @TedLyngmo - adding the free just now ! Commented Nov 2, 2023 at 23:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.