簡體   English   中英

高 integer 是在我數組的最后一個 memory 位置隨機生成的

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

我用隨機數填充一個隨機大小的數組。 隨機數的值不應大於 1000。大多數情況下它工作正常,但有時當我運行程序時,最后一個 memory 位置會顯示大於 1000 的數字。我做錯了什么? 我缺少某種 NULL 終結器? 我是新手級別。

#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;
}

假設你的數組大小是 5,那么第一位是 0,第二位是 1,第三位是 2,第四位是 3,第五位是 4! 所以它的大小 - 1

因此,您應該像這樣編寫 for 循環:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM