The comments have highlighted many issues. Here are some of the same, some more, and some solutions.
The const char *
argument to atoi
does not mean a pointer to any character, but rather a pointer to a null-terminated sequence of non-zero bytes: a string.
On scanf
, briefly:
- Always check the return value is the expected number of conversions. Failing to do so means operating on indeterminate values.
%d
reads a signed integer, %u
reads an unsigned integer.
%c
reads a single character. Prefixing this specifier with a space ( %c
) causes it to skip leading whitespace.
%s
reads a string. Its argument must be a pointer to a buffer that can store multiple characters, with room for a null-terminating byte (hint: an array). Always limit this specifier to the size of the buffer, minus one.
char buffer[128];
if (1 != scanf("%127s", buffer))
/* uh oh */;
Had it worked, char parr1[cast2];
would only be able to a single string. You need an array of arrays to store multiple strings.
When creating a variable-length array, care must be taken to ensure the size is always a positive, non-zero integer that will not expend too much memory.
Calling rand
without first calling srand
(once) will lead to the same results every time you run the program.
Reading an integer (scanf("%d", &logic);
), and then using that value to determine the value of another variable (answer
), only to use the second value the same way you would have used the first is ... redundant.
while(answer=='y')
will never stop, as answer
does not change inside the loop.
This is, more-or-less, the program you were attempting to write.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
unsigned length;
printf("Choose array length: ");
if (1 != scanf("%u", &length) || 0 == length || length > 50)
return EXIT_FAILURE;
char names[length][100];
for (unsigned i = 0; i < length; i++) {
printf("Name to insert to array: ");
if (1 != scanf("%99s", names[i]))
return EXIT_FAILURE;
}
srand((unsigned) time(NULL));
while (1) {
char answer;
printf("Would you like to generate a new name? (y1 / n2): ");
if (1 != scanf(" %c", &answer))
return EXIT_FAILURE;
if (!strchr("y1", answer))
break;
puts(names[(unsigned) rand() % length]);
}
}
Input file for testing (./a.out < input
):
10
one
two
three
four
five
six
seven
eight
nine
ten
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyn
Output, abbreviated:
Would you like to generate a new name? (y1 / n2): one
Would you like to generate a new name? (y1 / n2): four
Would you like to generate a new name? (y1 / n2): nine
Would you like to generate a new name? (y1 / n2): ten
Would you like to generate a new name? (y1 / n2): five
Would you like to generate a new name? (y1 / n2): one
Would you like to generate a new name? (y1 / n2): seven
...