[c/c++]柔性数组

/ 6,819评论 / 36980阅读 / 0点赞

柔性数组

在C99标准之后,在结构体中最后一个元素允许是未知大小的,称之为柔性数组

struct CoolArr_s{
	int len;
	char arr[];
};
#include "stdio.h"
#include "stdlib.h"

struct CoolArr_s
{
        int len;
        char arr[];
};

int main()
{
        //这里给arr的长度为10个char的大小
        struct CoolArr_s* p = (struct CoolArr_s*)malloc(sizeof(int) + sizeof(char) * 10);
        for (int i = 10; i--;)
        {
                (p->arr)[i] = i + '0';
                printf("%d " ,(p->arr)[i]);
        }
        printf("\n CoolArr_s: %d, *p: %d\n", sizeof(struct CoolArr_s), sizeof(*p));
        return 0;
}

在C++中的柔性数组

注意:在c++中并不建议使用柔性数组,而应考虑使用array代替。即使它可以使用在struct和class中,但部分编译器是不支持这种操作的。

#include <iostream>
#include <array>
using namespace std;

int main()
{
        //数组长度
	const int len_arr = 10;
        //定义数组
	array<int, len_arr> arr;
        //array::data()返回数组的首地址
        //array::begin()返回的是迭代器iterator
	int *arr_p = arr.data();
	for (int i = len_arr; i--;)
	{
		arr_p[i] = i;
		cout << arr[i] << " ";
	}
	cout << endl;
	return 0;
}
  1. WilliamRen说道:

    http://cytotec.club/# Misoprostol 200 mg buy online

  2. MeganLiard说道:

    casino
    top casino games

  3. RonaldSwobe说道:

    http://cytotec.club/# Cytotec 200mcg price

  4. Davidfrify说道:

    order cytotec online cytotec online Cytotec 200mcg price

  5. Davidfrify说道:

    cheap propecia pill home buying propecia

  6. RonaldSwobe说道:

    https://nolvadex.life/# does tamoxifen cause bone loss

  7. Davidfrify说道:

    tamoxifen medication buy nolvadex online femara vs tamoxifen

  8. WilliamRen说道:

    http://cytotec.club/# п»їcytotec pills online

  9. RandallGuesE说道:

    lisinopril 20mg prices: zestril 10mg – lisinopril 80 mg tablet

  10. Matthewcon说道:

    Если сумма выигрыша превышает 5 млн рублей, 1Win имеет право установить индивидуальный лимит на вывод в сутки. Мобильная версия и приложения. Для юзеров, предпочитающих мобильные гаджеты, у «1Вин» есть мобильная версия и приложения на iOS и Android 1win

回复 THATHECOM 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注