0

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:

  1. the compiler accepts,
  2. won't crash the program, and
  3. 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;
NetVipeC
4,4321 gold badge20 silver badges20 bronze badges
asked Sep 1, 2014 at 17:49
1
  • 1
    You need to think about what ips[octets] is. Commented Sep 1, 2014 at 17:51

1 Answer 1

2

Rewrite this loop like

for (int a = 0; a < addresses; a++) {
 for (int o = 0; o < octets; o++) {
 ips[a][o] = rand() % 255;
 }
}
NetVipeC
4,4321 gold badge20 silver badges20 bronze badges
answered Sep 1, 2014 at 17:54
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.