I am completing an exercise in which I want to create an array and populate it with random and meaningless IP addresses.
It is supposed to be a 2 dimensional array[5][4]. It is 5 addresses, each consisting of 4 parts( i.e. {192, 168, 0 ,1}. My trouble comes from using the rand() function to populate only one dimension of the array. I cannot figure out how to do it in a way that:
- the compiler accepts,
- won't crash the program, and
- won't produce an entirely random result.
Although my main issue comes from the for loop for (int o = 0; o < octets; o++) below , feel free to comment on any of my code, best practices, etc.
#include <stdio.h>
#include <stdlib.h>
int main() {
const int addresses = 5, octets = 4;
int ips[addresses][octets];
for (int a = 0; a < addresses; a++) {
for (int o = 0; o < octets; o++) {
ips[octets] = rand() % 255;
}
}
for (int i = 0; i < addresses; i++) {
for (int j = 0; j < octets; j++) {
printf("%d ", ips[i][j]);
}
putchar('\n');
}
return 0;
}
The compiler error for this code is... :
ipAddressArray.c: In function 'main':
ipAddressArray.c:18:18: error: incompatible types when assigning to type 'int[(s
izetype)octets]' from type 'int' ps[octets] = rand()%255;
1 Answer 1
Rewrite this loop like
for (int a = 0; a < addresses; a++) {
for (int o = 0; o < octets; o++) {
ips[a][o] = rand() % 255;
}
}
ips[octets]is.