柔性数组
在C99标准之后,在结构体中最后一个元素允许是未知大小的,称之为柔性数组
- 一般定义为:
- 类型 变量名[]
- 注意:
- 结构体中,柔性数组前必须有变量
- 柔性数组必须定义在结构体的最后
- 示例:
struct CoolArr_s{
int len;
char arr[];
};
- -
- 如果编译器报错,则考虑把最后的 char arr[] 尝试替换为一下几种写法:
- char arr[0]
- char arr[1] (非常不推荐,如果这样声明后使用时会被认为是越界行为)
- 如果编译器报错,则考虑把最后的 char arr[] 尝试替换为一下几种写法:
- 使用 malloc(sizeof(int) + sizeof(char) * 长度) 申请内存空间
- 示例:
#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;
}
- 运行结果:
- 那么这和直接把它定义为指针有什么区别呢?或者说它有什么好处呢?
- 首先从上面的例子的运行结果可见,结构体 CoolArr_s 的大小就是 int len 的大小。也就是说,柔性数组 char arr[] 并不会占一个指针的大小。数组名 arr 是一个常量地址,这个地址是紧接着 int len 的后面的地址。(数组名和指针是不同的)
- 其次就是柔性数组的内存空间是和结构体连续的,而声明为指针时,其指向的数组内存空间和结构体极大概率不是连续的。这一点在给一些函数传值时是非常重要的区别,比如 linux中的消息队列 相关的函数。
在C++中的柔性数组
注意:在c++中并不建议使用柔性数组,而应考虑使用array代替。即使它可以使用在struct和class中,但部分编译器是不支持这种操作的。
- 截止至2022(C++20标准):
- 在g++中是可以使用柔性数组的
- 在VS2022的MSVC中使用柔性数组,虽然可以运行,但会有警告:
- warning C4200: 使用了非标准扩展: 结构/联合中的零大小数组
- warning C6011: 取消对 NULL 指针 “xxx” 的引用
- 所以在c++中应考虑使用array容器代替。
- 示例(使用array容器代替上面的例子):
#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;
}
view website short squeeze hamster kombat
купить квартиру в новостройке https://kvartiranovostroi2.ru
Привет!
Мы готовы предложить дипломы психологов, юристов, экономистов и других профессий по выгодным ценам.
lgzprojects.co.za/2024/06/30/куплю-диплом-рф/
Привет!
Покупка диплома о среднем полном образовании: как избежать мошенничества?
vk.com/unikvseru?w=wall414329581_6815
Всегда вам поможем!.
Здравствуйте!
Быстрая схема покупки диплома старого образца: что важно знать?
moregasmsplease.com/component/kunena/user/564237-ydekic
Будем рады вам помочь!.
Common Feedback and Suggestions
ivermectin buy online
Добрый день!
Купить документ о получении высшего образования вы сможете у нас в Москве.
ast-diplomy.com/kupit-diplom-krasnodar
и§Ђй»ћ
Привет, друзья!
Быстрое обучение и получение диплома магистра – возможно ли это?
landik-diploms-srednee.ru/svidetelstvo-o-rozhdenii В
Добрый день!
Купить документ о получении высшего образования
ast-diplomas24.ru/kupit-diplom-ekaterinbur
й›Јзљ„
Добрый день!
Мы изготавливаем дипломы любых профессий по доступным ценам.
blog.filmfabrique.net/2024/06/купить-диплом-казань/
Привет!
Мы предлагаем дипломы любых профессий по разумным ценам.
worldgonews.ru/diplomyi-ot-luchshih-vuzov
ж•…дє‹
Discover your perfect stay with WorldHotels-in.com, your ultimate destination for finding the best hotels worldwide! Our user-friendly platform offers a vast selection of accommodations to suit every traveler’s needs and budget. Whether you’re planning a luxurious getaway or a budget-friendly adventure, we’ve got you covered with our extensive database of hotels across the globe. Our intuitive search features allow you to filter results based on location, amenities, price range, and guest ratings, ensuring you find the ideal match for your trip. We pride ourselves on providing up-to-date information and competitive prices, often beating other booking sites. Our detailed hotel descriptions, high-quality photos, and authentic guest reviews give you a comprehensive view of each property before you book. Plus, our secure booking system and excellent customer support team ensure a smooth and worry-free experience from start to finish. Don’t waste time jumping between multiple websites – http://www.WorldHotels-in.com brings the world’s best hotels to your fingertips in one convenient place. Start planning your next unforgettable journey today and experience the difference with WorldHotels-in.com!
е‡єз”џ
е†Ќж¬Ў
coindarwin price analysis
The Hidden Account Behind Solana’s Architect Toly’s Triumph
Post A Pair of Portions of Java with a Brew
Toly, the innovator behind Solana, commenced his quest with an ordinary ritual – two coffees and a brew. Unaware to him, these occasions would spark the machinery of his future. At present, Solana is as a powerful contender in the crypto sphere, having a billion-dollar market value.
Ethereum ETF First Sales
The Ethereum exchange-traded fund recently made its debut with a staggering trading volume. This historic event experienced several spot Ethereum ETFs from multiple issuers start trading in the U.S., bringing significant activity into the generally calm ETF trading market.
SEC’s Approval of Ethereum ETF
The SEC has officially approved the Ethereum Spot ETF to be listed. As a cryptographic asset with smart contracts, Ethereum is expected to majorly affect the digital currency industry with this approval.
Trump’s Bitcoin Strategy
As the election draws near, Trump frames himself as the “President of Crypto,” repeatedly showing his endorsement of the blockchain space to gain voters. His strategy is different from Biden’s strategy, targeting the interest of the blockchain community.
Elon Musk’s Impact
Elon Musk, a notable figure in the cryptocurrency space and a proponent of Trump’s agenda, stirred things up once more, promoting a meme coin related to his antics. His engagement continues to shape market trends.
Binance’s Latest Moves
Binance’s unit, BAM, has been permitted to allocate customer funds in U.S. Treasuries. Furthermore, Binance observed its seventh anniversary, showcasing its path and securing numerous regulatory approvals. Simultaneously, the company also revealed plans to remove several major crypto trading pairs, affecting different market players.
AI’s Impact on the Economy
A top stock analyst from Goldman Sachs recently observed that AI is unlikely to cause a major economic changeHere’s the spintax version of the provided text with possible synonyms
проверенные капперы проверенные капперы .
и»Љ
Добрый день!
Приобрести документ о получении высшего образования можно у нас.
diplomyx.com/kupit-diplom-s-registraciej
Привет, друзья!
Купить документ университета вы можете у нас в столице.
ast-diploms.com/kupit-diplom-o-vysshem-obrazovanii
birminghamnews24.com
Online Platforms Offering the Game
ivermectin buy online
еєЉ
белый список капперов телеграмм https://rejting-kapperov12.ru/ .
africanownews.com
купить однокомнатную квартиру в новостройке купить новостройку цены застройщика
дёЌ
оборудование конференц зала оборудование конференц зала .
проверенные капперы проверенные капперы .
лучшие капперы с бесплатными прогнозами лучшие капперы с бесплатными прогнозами .
paxlovid for sale: paxlovid buy – paxlovid pharmacy
Добрый день!
Мы предлагаем дипломы любой профессии по приятным ценам.
onlinekinospace.ru/kupite-diplom-dlya-vashego-budushhego
конференц залы оснащение конференц залы оснащение .
е€°
Привет, друзья!
Приобрести диплом ВУЗа.
midoma.ru/node/shirokiy-vybor-dokumentov-v-izvestnom-interne
Здравствуйте!
Приобрести диплом о высшем образовании.
livestockkenya.com/index.php/cb-profile/pluginclass/cbblogs?action=blogs&func=show&id=244
лучшие капперы в телеграмме лучшие капперы в телеграмме .
Paxlovid over the counter: Paxlovid over the counter – paxlovid buy
оборудование для конференц зала оборудование для конференц зала .
оборудование для конференц связи http://oborudovanie-dlja-konferenc-zalov.ru/ .
Здравствуйте!
Аттестат 11 класса купить официально с упрощенным обучением в Москве
newsbig.raidersfanteamshop.com/poleznye-sovety-po-priobreteniu-diploma-v-internete/
з©єй–“
can you buy generic clomid no prescription: clomid for sale – clomid generics
иЎЁйЃ”
馬上
Всё о покупке аттестата о среднем образовании: полезные советы
ast-diploms24.ru/kupit-diplom-sankt-peterburg
Evolution and Technological Advancements
ivermectin purchase
命令