简体   繁体   中英

High integer is generated in the last memory location of my array randomly

I populate a randomly sized array with random numbers. The random numbers should not have a value greater than 1000. Mostly it works fine, but occasionally when I run the program the last memory location will show a number higher than 1000. What am I doing wrong? Some kind of NULL terminator I am missing? I am Novice level.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define Random(high, low) (rand() % (high - low)) + low
int * GetArray(int);

int main()
{
    srand(time(NULL)); 
    int num = Random(15, 5);
    GetArray(num);

    return 0;
}

int * GetArray(int size){
    int* ptr = (int*)malloc(size * sizeof(int));
    for(int x = 0;x < size;x++){
        ptr[x] = Random(1000,1);
        }
    printf(" Forward: ");
    for (int x=0; x<=size; x++){
        printf("a[%d]=%d  ",x, ptr[x]);
    }
    printf("\r\nBackward: ");
    for (int x=size; x >=0 ; x--){
         printf("a[%d]=%d  ",x, ptr[x]);
    }
    return ptr;
}

Imagine that size of your array is 5, so the first place is 0, second one is 1, third is 2, fourth is 3 and fifth is 4! So its size - 1

Thus you should write your for loop like this:

for(int x = 0; x < size; x++)

And

for(int x = size - 1; x >= 0; x--)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM