[英]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?随机数的值不应大于 1000。大多数情况下它工作正常,但有时当我运行程序时,最后一个 memory 位置会显示大于 1000 的数字。我做错了什么? Some kind of NULL terminator I am missing?我缺少某种 NULL 终结器? 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!假设你的数组大小是 5,那么第一位是 0,第二位是 1,第三位是 2,第四位是 3,第五位是 4! So its size - 1所以它的大小 - 1
Thus you should write your for loop like this:因此,您应该像这样编写 for 循环:
for(int x = 0; x < size; x++)
And和
for(int x = size - 1; x >= 0; x--)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.