对指定位进行设置的函数c++
时间: 2023-12-16 15:03:42 浏览: 8
您可以使用C++的数组或指针来设置指定位的值。以下是一个使用数组的示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
int arr[10] = {0}; // 声明一个长度为10的数组并初始化为0
int index = 5; // 希望设置的位数
int value = 100; // 希望设置的值
arr[index] = value; // 设置指定位的值
cout << "arr[" << index << "] = " << arr[index] << endl; // 输出设置后的结果
return 0;
}
```
该程序将输出:
```
arr[5] = 100
```
如果您希望使用指针来设置指定位的值,可以使用以下代码:
```c++
#include <iostream>
using namespace std;
int main() {
int* ptr = new int[10]; // 声明一个长度为10的动态数组
int index = 5; // 希望设置的位数
int value = 100; // 希望设置的值
*(ptr + index) = value; // 设置指定位的值
cout << "*(ptr+" << index << ") = " << *(ptr + index) << endl; // 输出设置后的结果
delete[] ptr; // 释放内存
return 0;
}
```
该程序将输出:
```
*(ptr+5) = 100
```