#include <stdio.h>
#include <stdlib.h>
#define N 3
#define M 10
/* run this program using the console pauser or add your own getchsystem("pause") or input loop */
int main(int argc, char *argv[]) {
srand(time()); //to generate each run different numbers
char str [N][M];
int i,j;
i=0;
str [0][0]="good";
str[1][M]="morning";
str[2][M]="world";
for (j=0;j<N; j++) {
i=rand()%(N-0+1)+1; //formula to generate randoms numbers
printf("%s",str[i]);
}
return 0;
}
2 Answers
First, turn on compilation warnings. You should get warnings because your code isn't valid. For example, with gcc I get:
randstr.c: In function ?main?:
randstr.c:16:15: warning: assignment makes integer from pointer without a cast [enabled by default]
str [0][0]="good";
^
randstr.c:17:14: warning: assignment makes integer from pointer without a cast [enabled by default]
str[1][M]="morning";
^
randstr.c:18:14: warning: assignment makes integer from pointer without a cast [enabled by default]
str[2][M]="world";
This is because you are assigning character string pointers to char elements in the array, and each char element holds one character (generally, 8 bits.)
A simpler way to code this would be to use char *str[N] rather than char str[N][M].
But the reason your program crashes with segmentation fault is that time() takes an argument, and you're not passing one. Try time(NULL).
Here's how it would be coded using char *str[N]:
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main(int argc, char *argv[]) {
srand(time(NULL)); //to generate each run different numbers
char *str[N];
int i,j;
str[0] = "good";
str[1] = "morning";
str[2] = "world";
for (j=0; j<N; j++) {
i = rand() % N; //formula to generate randoms numbers
printf("%s\n",str[i]);
}
return 0;
}
Comments
There's a few things wrong with your code here.
In C, you cannot assign strings using the assignment operator unless it's a string pointer or you're initializing. See here for the man page on strcpy.
Using the above method, you can define your strings like so:
strcpy(str[0], "good");
strcpy(str[1], "morning");
strcpy(str[2], "world");
Your rand function call should also just be
i = rand() % N;
When you were calling str[N][M] you were actually accessing a single character of the string rather than the whole thing. ex.
str[0][0] = 'g'
str[0][1] = 'o'
str[1][0] = 'm'
str[1][1] = 'o'
=to copy a string, please usestrcpy. The=syntax can only be used for a string pointer, or when initialising an array in the statement where it is defined. You should enable all compiler warnings and act on them. "I know that arrays in C are seen like pointers" is a partial truth - when they are passed to a function.i = rand() % N;is correct, noti = rand() % (N+1) + 1;strcpy(str[0], "good");and so on.str[x][y]you're accessing a singlechar. A string is a NUL-terminated array ofchars. Locationsstr[0],str[1], andstr[2]each containMchars, so your strings can be maxM-1chars long each (the last char in the string must be 0).