0

I'm new to C. I'm trying to think of a way that I can ask a user to define the length of an array. Can yall give me an example for doing this? I know this dosnt work as it gives me a segmentation fault. Just need an example so I can rewrite my code. Thanks!

   case 3:
               srand(time(NULL));
               printf("How many time do you want to roll a dice? ");
               scanf("%d", &DiceRoll);

               for (k = 0; k < DiceRoll;++k)
                   {
                    MyArray[p] = rand()% 6 +1;
                   }
               DiceFill(MyArray,DiceRoll);
               break;
MikeCAT
  • 73,922
  • 11
  • 45
  • 70

2 Answers2

1

You can use malloc() to allocate buffer.

int* MyArray; /* declaretion of pointer variable: use the type you want to use for element */

/* ... */

case 3:
    srand(time(NULL));
    printf("How many time do you want to roll a dice? ");
    if (scanf("%d", &DiceRoll) != 1) /* you should check if readings are successful */
    {
        puts("read error");
        break;
    }

    MyArray = malloc(sizeof(*MyArray) * DiceRoll); /* allocate buffer */
    if (MyArray == NULL) /* check if allocation is successful /*/
    {
        perror("malloc");
        break;
    }
    for (k = 0; k < DiceRoll;++k)
    {
        MyArray[p] = rand()% 6 +1;
    }
    DiceFill(MyArray,DiceRoll);
    break;

Note: Your usage of srand() isn't completely bad, but smells. Related article: c - srand() — why call it only once? - Stack Overflow

Community
  • 1
  • 1
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

There are some problems with the above code, it doesn't matter how many times the user asks to roll dice as you only put the last result in MyArray[p] (p doesn't change throughout the for loop).

to answer your question, you can use malloc as people have answered like so:

int *MyArray = malloc(sizeof(int) * some_array_size);

as of C-90 you can also allocate the array on the stack like so:

int[some_array_size] MyArray;

hope this helps

monkeyStix
  • 620
  • 5
  • 10