我寫下的代碼:
#include<stdio.h>
#include<stdlib.h>
void get()
{
int i,a[50],limit;
printf("enter the limit:");
scanf("%d",&limit);
printf("enter the array");
for(i=0;i<limit;i )
{
scanf("%d",&a[i]);
}
}
void display()
{
int i,a[50],limit;
printf("the array is");
for(i=0;i<limit;i )
{
printf("%d\t",a[i]);
}
}
int main(void)
{
int i,a[50],limit;
get();
display();
}
輸出:
enter the limit:5
enter the array1
2
3
4
5
the array is1 2 3 4 5 7143534 7209061 7536756 6488156 7077985 2949228 7471201 3019901633014777 7864421 101 0 0 -707682512 32767 -317320272 573 -690587167 32767 -317320288 573 -317325312 573 47 064 0 0 0 4 0 0 0-317325312 573 -690580068 32767 -31732531573 2 0 47 0 64 51 -1799357088 125 961877721 32758 3 32758 961957944 32758 -317168624 573 -706746576 32767
uj5u.com熱心網友回復:
當您int i,a[50],limit;在每個函式中宣告時,這些變數是函式的本地變數。
例如,宣告的limit變數與宣告的變數等get完全無關。它們恰好具有相同的名稱。limitset
您需要將這些變數宣告為全域變數(設計不佳),或者以不同的方式重新設計您的代碼,例如通過將這些變數作為引數傳遞。
所有這些都在初學者的 C 教科書的第一章中進行了解釋。
使用全域變數的示例(設計不佳)
#include <stdio.h>
#include <stdlib.h>
int i, a[50], limit; // global variables visible
// from all functions
void get()
{
printf("enter the limit:");
scanf("%d", &limit);
printf("enter the array");
for (i = 0; i < limit; i )
{
scanf("%d", &a[i]);
}
}
void display()
{
printf("the array is");
for (i = 0; i < limit; i )
{
printf("%d\t", a[i]);
}
}
int main(void)
{
get();
display();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483005.html
