常量数组

#include<stdio.h>
char s[] = "`123456780-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";//常量数组往往能够简化代码,并且常量数组不需要声明大小,编译器能够处理
int main()
{
    char c;
    int i;
    while((c = getchar()) !=EOF)
    {
        for(i =1; s[i] && s[i] != c ;i++);
        if(s[i])
            putchar(s[i-1]);
        else
            putchar(c);
    }
    return 0;
}
在 C/C++ 编程中,结构体包含常量数组可以通过多种方式实现,具体取决于使用场景和需求。以下是一些常见的方法和注意事项。 ### 在结构体中定义常量数组 可以在结构体内部直接定义常量数组,但需要注意数组大小必须是编译时常量。例如: ```cpp struct Example { const int values[3]; // 常量数组 }; ``` 但需要注意的是,C++ 中不能直接在结构体中初始化常量数组,必须在构造函中进行初始化。例如: ```cpp struct Example { const int values[3]; Example() : values{1, 2, 3} {} // 在构造函中初始化常量数组 }; ``` ### 使用 `static const` 定义类内常量数组 如果希望数组在所有对象之间共享,可以使用 `static const` 修饰符来定义类内的常量数组: ```cpp struct Example { static const int values[3]; }; // 在类外定义并初始化常量数组 const int Example::values[3] = {1, 2, 3}; ``` 这种方式适用于需要在多个对象之间共享的常量据。 ### 使用 `std::array` 或 `std::vector` 如果使用 C++11 或更高版本,可以考虑使用 `std::array` 来定义固定大小的常量数组,或者使用 `std::vector` 来定义动态大小的数组: ```cpp #include <array> struct Example { const std::array<int, 3> values; Example() : values{1, 2, 3} {} }; ``` 对于动态大小的数组,可以使用 `std::vector`: ```cpp #include <vector> struct Example { const std::vector<int> values; Example(size_t size) : values(size) {} }; ``` ### 使用柔性数组(C 语言特性) 在 C 语言中,可以使用柔性数组(Flexible Array Member, FAM)来实现结构体中包含可变长度的数组[^2]: ```c struct SoftArray { int len; int array[]; // 柔性数组 }; // 动态分配内存 struct SoftArray* createSoftArray(int len) { struct SoftArray* sa = (struct SoftArray*)malloc(sizeof(struct SoftArray) + len * sizeof(int)); sa->len = len; return sa; } ``` 这种方式允许结构体包含一个大小可变的数组,适合需要动态分配数组大小的场景。 ### 示例:结构体包含常量数组 以下是一个完整的示例,展示如何在 C++ 中定义包含常量数组的结构体: ```cpp #include <iostream> struct Example { static const int values[3]; void printValues() const { for (int i = 0; i < 3; ++i) { std::cout << values[i] << " "; } std::cout << std::endl; } }; // 类外定义常量数组 const int Example::values[3] = {1, 2, 3}; int main() { Example ex; ex.printValues(); // 输出: 1 2 3 return 0; } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值