Reputation: 1
I want to print random chars and save them all in one array. But the problem is, the array saves something - but not the chars printed/generated before. Does anybody know how to fix this?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
char get_symbol(int m);
int main()
{
srand(time(NULL));
char array[1][5];
char y;
int i;
for(i=0; i<5; i++){
y = get_symbol(rand()%3);
printf("%c", sym);
y = array[i];
}
printf("\n\n");
for(i=0; i<5; i++){
printf("%s", array[i]);
}
}
char get_symbol(int m){
char s;
switch(m){
case 0: s = 'A'; break;
case 1: s = 'B'; break;
case 2: s = 'C'; break;
default: break;
}
return s;
}
Upvotes: 0
Views: 52
Reputation: 50912
You probably want this, explanations are in the comments:
int main()
{
srand(time(NULL));
char array[5]; // you just want an array of 5 chars
char y;
int i;
for (i = 0; i < 5; i++) {
y = get_symbol(rand() % 3);
printf("%c", y); // sym is unknown, you probably wanted to print y
array[i] = y; // you have reversed the assignment
}
printf("\n\n");
for (i = 0; i < 5; i++) {
printf("%c", array[i]); // use %c here, you want to print 5 single chars
} // not 5 strings
fflush(stdout); // flush output buffer. maybe not necessary
}
Bonus:
Your get_symbol
function is overly complicated: this does exactly the same:
char get_symbol(int m) {
return 'A' + m % 3;
}
It also does the modulo operation inside the function because (at least in your original function) calling get_symbol
with values out side the interval [0..2] will lead to undefined behaviour.
Upvotes: 1