使用指针修改数组中的索引

时间:2015-03-02 07:06:04

标签: arrays

我试图仅使用指针修改数组。

void modify(){
int *ptr = &b[2];
*ptr = 90;
}

//I have my main function  
void main() {
  int b[15];
//fill the array with values using loop..skipping this part 
 modify();
}

它给我的错误是:错误:使用未声明的标识符' b'

任何人都可以给我一些见解,为什么编译器不能识别数组b?

1 个答案:

答案 0 :(得分:3)

bmain()中声明为局部变量,因此只能由main()访问。要使b对其他函数可见,请通过在任何函数之外声明它使其成为全局变量:

int b[3];

void modify(){
    int *ptr = &b[2];
    *ptr = 90;
}

int main(void) { //This is one of the standard signatures of main
    //Fill the array with values using a loop
    modify();
    return 0; //main returns an int
}