0

I have been reviewing videos in Walkthrough section from week 2 and decided to implement ages example. After I've implemented it I decide to extend it so program will prompt user fro name and display it. Here goes the code:

#include <stdio.h>
#include <cs50.h>

int main(void) 
{
    int n = 0;
    int s = 0;
    do 
    {
        printf("Please enter number of people in a room: ");
        n = GetInt();
    }
    while (n < 1);

    int ages[n];
    char* names[s];

    for (int i = 0; i < n; i++)
    {
        printf("Please enter name of person #%d: ", i+1);
        names[i] = GetString(); 
    }

    for (int i = 0; i < n; i++)
    {
        printf("Please enter age of %s: ", names[i]);
        ages[i] = GetInt(); 
    }
    printf("Time passes...\n");

    for (int i = 0; i < n; i++)
    {
        printf("A year from now, age of %s will be %d\n", names[i], ages[i] + 1); 
    }
}

However after certain point it throws out Segmentation Fault (core dumped) error. I have found out that names[i] in the last for loop is a cause of the problem, when it is gone everything works fine.Can you point out what is the wrong with it? Your help is very much appreciated!

1 Answer 1

1

Take a look at the following lines:

You first declare s as an integer, and initialize it to 0.

int s = 0;

Then you create an array of char* names which is the same as string names, but you tell it that it's length will be s, so it will have 0 members.

char* names[s];

Then you try to assign a name given by the user, to name[0], name[1] and so on, but earlier you said there will be no members in name, so you get a segfault.

for (int i = 0; i < n; i++)
{
    printf("Please enter name of person #%d: ", i+1);
    names[i] = GetString(); 
}

A solution would be to delete s altogether and use n for the lengths of your arrays.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

2
  • It worked, thanks a lot! But the thing is that int n follows the same pattern, but it doesn't give this problem. Is it because int n deals with array of integers and int s deals with array of strings?
    – user9453
    Commented Sep 4, 2015 at 8:43
  • No. In your do-while loop you change n with that n = GetInt();, so it's not 0, as you initialized it. s wasn't changing anywhere.
    – ChrisG
    Commented Sep 4, 2015 at 9:38

You must log in to answer this question.