Reputation: 19
So I am learning C, and I am trying to make a quick program that takes your name and age then greets you. This is what I have:
#include <stdio.h>
typedef struct {
char * name;
int age;
} person;
int main()
{
person p1;
scanf("%s", p1.name);
scanf("%d", p1.age);
printf("Hello, %s, you are %d years old!\n", p1.name, p1.age);
return 0;
}
The error I am getting is:
Segmentation fault (core dumped)
What is the issue with my basic code?
Upvotes: 1
Views: 77
Reputation: 26335
Something like this will help. I wrote this a while ago, and just changed it for your needs. It uses malloc()
to initialize memory for the string, and then uses free()
to release it at the end.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char * name;
int age;
} person_t;
int
main(void) {
person_t person;
char *name;
int str_size = 1, word_len = 0;
int ch;
/* allocates initial memory for the string */
name = malloc((str_size+1) *sizeof(*name));
/* builds char array, allocating more space when needed */
printf("Enter name: ");
while ((ch = getchar()) != '\n') {
/* new character found, but is there space? */
if (str_size == word_len) {
str_size *= 2;
name = realloc(name, str_size *sizeof(*name));
}
name[word_len++] = ch;
name[word_len] = '\0';
}
/* duplicates string into structure variable */
/* Using strdup() from string.h library */
person.name = strdup(name);
/* processes age */
printf("Enter age: ");
if (scanf("%d", &(person.age)) != 1) {
printf("Invalid age!\n");
exit(EXIT_FAILURE);
}
printf("Hello %s, you are %d years old!\n", person.name, person.age);
/* frees run-time array at the end */
/* Very important when using malloc() */
free(name);
return 0;
}
I hope this helps. I included some comments to make sure the code is clearer for you.
Upvotes: 3
Reputation: 14659
scanf("%s", p1.name);
You need to allocate enough space. You haven't allocated anything. You can use malloc(3) to allocate adequate space, but make sure you don't overflow p1.name. Look into the modifers to the format strings in scanf(3)
Upvotes: 2