Louie Wouters Louie Wouters - 3 months ago 10
C Question

assigning variable strings too an array with C

The goal of my code is to have the user, put in any amount of students as an integer and then have the program ask over and over to set a name too every integer (student)

I've been trying so many different things and I've been working on this without using any outside help for hours but I just couldn't figure this out. (if its something obvious, please don't get supermad, I'm only a beginner)

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

int main (void)
{
printf("How many students are there? ");
int amount = atoi(GetString());
printf("amount = %i\n", amount);
char *names[amount];

for(int i = 0; i < amount; i++)
{
printf("Enter the ellement #%d :", i +1);
scanf("%s", names[i]);
}

for (int i = 0; i == 0;)
{
printf("Acces student: ");
string search = GetString();
int searchnr = atoi(search);
printf("Student #%d is %s\n", searchnr, names[searchnr]);
}
}

>

}

Answer

The obvious solution:

for (int i = 0; i < amount; i++) {
    printf("Enter element #%d: ", i + 1);
    names[i] = GetString();
}

As to the second loop: it's an infinite loop. What is the terminating condition? You need to put that into the condition of the for loop else it will never terminate.

If your intent is getting an infinite loop, then a more readable, less confusing, more idiomatic solution is

while (1) {
    // ...
}

or

for (;;) {
    // ...
}