I must write a function which gets 30 names without repeated names and after that it prints random on name of this 30. But when I run the program after my second name I entered, I get Segmentation fault and I don't know why. Cause when I put the first name every thing is good.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#define SIZE 30 /*The size of the array of names*/
#define MAX_L 21 /*The length of a name included the ending 0*/
#define REPEAT 10 /*The amount of getting a random name in the names list */
char names[SIZE][MAX_L];/* = { 0 } ; /*Global array for the names we get from the users*/
/*Gives back a random name in an array nameslist*/
char * get_name(){
int random; /*the random index we get of the names list*/
char *r; /*the string name to return*/
random= rand()%SIZE; /*picks a random number from 0-29 */
r= names[random]; /*r points to the random name in the list*/
return r;
}
/*Gets from user 30 names without repeat and calls after that function get_names 10 times*/
int main(){
int i; /*counter for array names list */
int j; /*counter for array in the first inner loop to check if there are repeated names*/
int k; /*counter for the repeat loop for random names*/
int w; /*counter for the index of the character in the string */
bool same = true; /*says if two strings are the same or not*/
for (i=0; i< SIZE; i++){ /*Gets from the user 30 names and initialize them in the array*/
printf("\nPlease enter a name (repeated names forbidden until we'll get to 30 names)\n");
scanf("%s", names[i]);
if (i>0){
for (j=0; j<i; j++){ /*checks if is a repeated name or not*/
for (w=0; w< MAX_L || same ==false; w++){
if (names[i][w] != names[j][w]){
if (names[i][w] >= 'a' && names[i][w] <= 'z'){
if (names[i][w] - 32 != names[j][w])
same=false;}
else if (names[i][w] >= 'A' && names[i][w] <= 'Z'){
if (names[i][w] + 32 != names[j][w])
same=false;}
}
}
if (same ==true){ /*repeated name*/
printf("\nERROR! You already entered this name!");
return 0;}
}}
printf("\nThe name you entered is: %s\n", names[i]);
}
for (k=0; k<REPEAT; k++){ /*Calls the function get_name 10 times to get 10 random names from the array*/
printf("\nThe random name you got from the list is: %s", get_name());
}
return 0;
}
return r;w< MAX_L || same ==falseThat looks pretty dangerous. The point ofw<MAX_Lis to ensure the array bounds are not exceeded. Adding||potentially removes that safety barrier.sametotrueorfalse. Just useif (same)orif( !same ). It is too easy to mistype the number of equal signs, creating an error that is usually very difficult to find.