目录搜索
AlgorithmsAlgorithms(算法)bsearchbsearch_sqsortqsort_sAtomic operationsAtomic operations library(原子操作库)ATOMIC_*_LOCK_FREEatomic_compare_exchange_strongatomic_compare_exchange_strong_explicitatomic_compare_exchange_weakatomic_compare_exchange_weak_explicitatomic_exchangeatomic_exchange_explicitatomic_fetch_addatomic_fetch_add_explicitatomic_fetch_andatomic_fetch_and_explicitatomic_fetch_oratomic_fetch_or_explicitatomic_fetch_subatomic_fetch_sub_explicitatomic_fetch_xoratomic_fetch_xor_explicitatomic_flagatomic_flag_clearatomic_flag_clear_explicitATOMIC_FLAG_INITatomic_flag_test_and_setatomic_flag_test_and_set_explicitatomic_initatomic_is_lock_freeatomic_loadatomic_load_explicitatomic_signal_fenceatomic_storeatomic_store_explicitatomic_thread_fence(线程围栏)ATOMIC_VAR_INITkill_dependencymemory_order(内存排序)C keywordsauto(自动存储)break(跳出循环)C keywords(关键词)casecharconst(常量修饰符)continuedefault(预设运算式)dodouble(双精度浮点型)elseenum(枚举类型)extern(全局变量)float(浮点数)forfortrangoto(goto语句)if(if语句)inline(行内函式)intlong(长整型)register(寄存器变量)restrict( restrict类型限定符)returnshortsignedsizeof(sizeof运算符)static(静态变量)struct(结构体)switch(switch语句)typedef(typedef关键字)union(联合体)unsigned(无符号)void(空类型)volatile(volatile变量)while(while语句)_Alignas_Alignof_Atomic_Bool_Complex_Generic_Imaginary_Noreturn_Static_assert_Thread_localC language#define directive#elif directive#else directive#endif directive#error directive#if directive#ifdef directive#ifndef directive#include directive#line directive#pragma directivealignas(对齐指定符)Alternative operators and tokens(替代运算符和令牌)AnalyzabilityArithmetic operatorsArithmetic typesArray declaration(数组声明)Array initialization(阵列初始化)ASCII ChartAssignment operators(赋值运算符)types(atomic类型限定符)Basic conceptsBit fields(位域)break statementC languageC Operator Precedencecast operatorcharacter constant(字符字面量)Comments(注释符)Comparison operators(比较运算符)compound literals(符合字面量)Conditional inclusion(条件包含)Conformance(一致性)const type qualifier(const 限定符)Constant expressions(常量表达)continue statementDeclarations(声明)do-while loopEnumerations(枚举类型)Escape sequences(转义字符)Expressions(表达式)External and tentative definitions(外部和暂定的定义)File scope(文件范围)floating constant(浮点常量)for loopFunction declarations(函数声明)Function definitions(函数声明)FunctionsGeneric selection泛型选择goto statementIdentifier(标示符)if statementImplicit conversions(隐式转换)Increment/decrement operators(前置/后置操作符)Initialization(初始化)inline function specifier(内联函式)integer constantLifetime(生命期)Logical operators(逻辑运算符)Lookup and name spacesMain function(主函式)Member access operators(会员接入运营商)Memory modelObjects and alignment(字节对齐)Order of evaluation(评估顺序)Other operatorsPhases of translation(翻译阶段)Pointer declarationPreprocessor(预处理)restrict type qualifier(restrict类型限定符)return statementScalar initialization(标量类型初始化)Scope(范围)sizeof operator(sizeof运算符)Statements(陈述)static assert declaration(静态断言声明)Static storage duration(静态存储周期)Storage-class specifiers(存储类说明符)string literals(字符串字面量)Struct and union initialization(结构体与联合体初始化)Struct declaration(结构体声明)switch statementThread storage duration(线程存储时间)TypeType(类型)Typedef declaration(Typedef声明)Undefined behavior(未定义行为)Union declaration(联合体声明)Value categories(值类别)Variadic arguments(变长参数宏)volatile type qualifier(volatile 类型限定符)while loop_Alignof operator_Noreturn function specifierDate and timeasctime(asctime函数)asctime_sclockCLOCKS_PER_SECclock_tctime(ctime函数)ctime_sDate and time utilities(日期和时间库)difftime(计算两个时间的间隔)gmtimegmtime_slocaltimelocaltime_smktime(将时间结构数据转换成经过的秒数的函数)strftime(格式化输出时间函数)timetimespectimespec_gettime_ttmwcsftime(格式化时间宽字符)Dynamic memory managementaligned_allocC memory management library(内存管理库)callocfree(释放动态分配空间的函数)malloc(动态分配内存空间的函数)realloc(重新分配内存空间的函数)Error handlingabort_handler_sassert(断言)constraint_handler_terrno(错误报告)Error handling(错误处理)Error numbers(错误个数)ignore_handler_sset_constraint_handler_sstatic_assertFile input/outputclearerr(清除/复位)fclosefeofferrorfflush(清空文件缓冲区)fgetcfgetposfgetsfgetwcfgetwsFile input/outputfopenfopen_sfprintffprintf_sfputcfputsfputwcfputwsfreadfreopenfreopen_sfscanffscanf_sfseekfsetposftellfwidefwprintffwprintf_sfwritefwscanffwscanf_sgetcgetchargetsgets_sgetwcharperrorprintfprintf_sputcputcharputsputwcputwcharremoverenamerewindscanfscanf_ssetbufsetvbufsnprintfsprintfsscanfsscanf_sswprintfswprintf_sswscanfswscanf_stmpfiletmpfile_stmpnamtmpnam_sungetcungetwcvfprintfvfprintf_svfscanfvfscanf_svfwprintfvfwprintf_svfwscanfvfwscanf_svprintfvprintf_svscanfvscanf_svsnprintfvsprintfvsscanfvsscanf_svswprintfvswprintf_svswscanfvswscanf_svwprintfvwprintf_svwscanfvwscanf_swprintfwprintf_swscanfwscanf_sLocalization supportlconvLC_ALLLC_COLLATELC_CTYPELC_MONETARYLC_NUMERICLC_TIMElocaleconvLocalization supportsetlocaleNumericsabsacosacosfacoshacoshfacoshlacoslasinasinfasinhasinhfasinhlasinlatanatan2atan2fatan2latanfatanhatanhfatanhlatanlcabscabsfcabslcacoscacosfcacoshcacoshfcacoshlcacoslcargcargfcarglcasincasinfcasinhcasinhfcasinhlcasinlcatancatanfcatanhcatanhfcatanhlcatanlcbrtcbrtfcbrtlccosccosfccoshccoshfccoshlccoslceilceilfceillcexpcexpfcexplcimagcimagfcimaglclogclogfcloglCMPLXCMPLXFCMPLXLCommon mathematical functionscomplexComplex number arithmeticconjconjfconjlcopysigncopysignfcopysignlcoscosfcoshcoshfcoshlcoslcpowcpowfcpowlcprojcprojfcprojlcrealcrealfcreallcsincsinfcsinhcsinhfcsinhlcsinlcsqrtcsqrtfcsqrtlctanctanfctanhctanhfctanhlctanldivdouble_terferfcerfcferfclerfferflexpexp2exp2fexp2lexpfexplexpm1expm1fexpm1lfabsfabsffabslfdimfeclearexceptfegetenvfegetexceptflagfegetroundfeholdexceptferaiseexceptfesetenvfesetexceptflagfesetroundfetestexceptfeupdateenvFE_ALL_EXCEPTFE_DFL_ENVFE_DIVBYZEROFE_DOWNWARDFE_INEXACTFE_INVALIDFE_OVERFLOWFE_TONEARESTFE_TOWARDZEROFE_UNDERFLOWFE_UPWARDFloating-point environmentfloat_tfloorfloorffloorlfmafmaffmalfmaxfmaxffmaxlfminfminffminlfmodfmodffmodlfpclassifyFP_INFINITEFP_NANFP_NORMALFP_SUBNORMALFP_ZEROfrexpfrexpffrexplHUGE_VALHUGE_VALFHUGE_VALLhypothypotfhypotlIilogbilogbfilogblimaginaryimaxabsimaxdivINFINITYisfiniteisgreaterisgreaterequalisinfislessislessequalislessgreaterisnanisnormalisunorderedlabsldexpldexpfldexplldivlgammalgammaflgammalllabslldivllrintllrintfllrintlllroundllroundfllroundlloglog10log10flog10llog1plog1pflog1pllog2log2flog2llogblogbflogbllogflogllrintlrintflrintllroundlroundflroundlMATH_ERREXCEPTmath_errhandlingMATH_ERRNOmodfmodffmodflnanNANnanfnanlnearbyintnearbyintfnearbyintlnextafternextafterfnextafterlnexttowardnexttowardfnexttowardlNumericspowpowfpowlPseudo-random number generationrandRAND_MAXremainderremainderfremainderlremquoremquofremquolrintrintfrintlroundroundfroundlscalblnscalblnfscalblnlscalbnscalbnfscalbnlsignbitsinsinfsinhsinhfsinhlsinlsqrtsqrtfsqrtlsrandtantanftanhtanhftanhltanltgammatgammaftgammaltrunctruncftrunclType-generic math_Complex_I_Imaginary_IProgram supportabortatexitat_quick_exitexitEXIT_FAILUREEXIT_SUCCESSgetenvgetenv_sjmp_buflongjmpProgram support utilitiesquick_exitraisesetjmpSIGABRTSIGFPESIGILLSIGINTsignalSIGSEGVSIGTERMsig_atomic_tSIG_DFLSIG_ERRSIG_IGNsystem_ExitStringsatofatoiatolatollbtowcc16rtombc32rtombchar16_tchar32_tisalnumisalphaisblankiscntrlisdigitisgraphislowerisprintispunctisspaceisupperiswalnumiswalphaiswblankiswcntrliswctypeiswdigitiswgraphiswloweriswprintiswpunctiswspaceiswupperiswxdigitisxdigitmblenmbrlenmbrtoc16mbrtoc32mbrtowcmbsinitmbsrtowcsmbsrtowcs_smbstate_tmbstowcsmbstowcs_smbtowcmemchrmemcmpmemcpymemcpy_smemmovememmove_smemsetmemset_sNull-terminated byte stringsNull-terminated multibyte stringsNull-terminated wide stringsstrcatstrcat_sstrchrstrcmpstrcollstrcpystrcpy_sstrcspnstrerrorstrerrorlen_sstrerror_sStrings librarystrlenstrncatThread supportcall_oncecnd_broadcastcnd_destroycnd_initcnd_signalcnd_timedwaitcnd_waitmtx_destroymtx_initmtx_lockmtx_plainmtx_recursivemtx_timedmtx_timedlockmtx_trylockmtx_unlockonce_flagONCE_FLAG_INITthrd_busythrd_createthrd_currentthrd_detachthrd_equalthrd_errorthrd_exitthrd_jointhrd_nomemthrd_sleepthrd_successthrd_timedoutthrd_yieldThread support librarythread_localtss_createtss_deleteTSS_DTOR_ITERATIONStss_gettss_setType supportBoolean type support libraryFixed width integer typesFLT_EVAL_METHODFLT_ROUNDSmax_align_tNULLNumeric limitsoffsetofptrdiff_tsize_tType supportVariadic functionsVariadic functionsva_argva_copyva_endva_listva_start
文字

当初始化一个数组类型的对象时,初始化器必须是一个字符串文字(可选地用大括号括起来)或者是一个由数组成员初始化的大括号括起来的列表:

= string_literal

(1)


= {  expression , ... }  = {  designator(optional) expression , ... }

(2)

(until C99)(since C99)

1)用于字符和宽字符数组的字符串字面初始值设定项

2)用逗号分隔的数组元素的初始值表达式列表,可选地使用形式为[constant-expression 的数组指示符] =  (自 C99开始)

已知大小的阵列和未知大小的阵列可能被初始化,但不是 VLA。(自 C99以来)。

所有未明确初始化的数组元素都是以与具有静态存储持续时间的对象相同的方式隐式初始化的。

从字符串初始化

字符串文字(可以用大括号括起来)可以用作匹配类型数组的初始值设定项:

  • 普通字符串文字和 UTF-8字符串(因为 C11)可以初始化任何字符类型的阵列(charsigned charunsigned char

  • 带前缀的宽字符串文字可用于初始化任何兼容的类型的数组(忽略 cv 资格) wchar_t

u-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications) char16_t   U-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications char32_t

(since C11)

  • 带 u 前缀的宽字符串文字可用于初始化任何兼容类型的数组(忽略 cv 资格) char16_t

  • 带U前缀的宽字符串文字可以用来初始化任何兼容类型的数组(忽略 cv 资格) char32_t

(since C11)

字符串文字的连续字节或宽字符串文字的宽字符(包括终止空字节/字符)初始化数组的元素:

char str[] = "abc"; // str has type char[4] and holds 'a', 'b'. 'c', '\0'wchar_t wstr[4] = L"猫"; // str has type wchar_t[4] and holds L'猫', '\0', '\0', '\0'

如果数组的大小已知,则它可能比字符串文字的大小小1,在这种情况下,将终止空字符被忽略:

char str[3] = "abc"; // str has type char[3] and holds 'a', 'b', 'c'

请注意,与使用直接访问字符串字面值不同,此数组的内容是可修改的char* str = "abc";

从大括号列表中初始化

当一个数组用初始化器的大括号初始化时,列表中的第一个初始化器初始化索引为0的数组元素(除非指定了指定符号)(自C99开始),并且每个后续的初始化器都没有指定符(自C99开始)初始化索引1处的数组元素大于前一个初始化器初始化的数组元素。

int x[] = {1,2,3}; // x has type int[3] and holds 1,2,3int y[5] = {1,2,3}; // y has type int[5] and holds 1,2,3,0,0int z[3] = {0}; // z has type int[3] and holds all zeroes

在初始化已知大小的数组时,提供比元素更多的初始化程序是错误的(除了从字符串文字初始化字符数组时)。

A designator causes the following initializer to initialize of the array element described by the designator. Initialization then continues forward in order, beginning with the next element after the one described by the designator. int n5 = {4=5,0=1,2,3,4} // holds 1,2,3,4,5   int aMAX = { // starts initializing a0 = 1, a1 = 3, ...     1, 3, 5, 7, 9, MAX-5 = 8, 6, 4, 2, 0 } // for MAX=6,  array holds 1,8,6,4,2,0 // for MAX=13, array holds 1,3,5,7,9,0,0,0,8,6,4,2,0 ("sparse array")

(since C99)

初始化未知大小的数组时,指定初始化程序的最大下标确定正在声明的数组的大小。

嵌套数组

如果数组的元素是数组,结构体或联合体,则大括号括起来的初始化程序中相应的初始化程序是对这些成员有效的任何初始化程序,除了它们的大括号可以省略如下:

如果嵌套的初始化程序以开始大括号开始,则整个嵌套初始化程序直到其大括号初始化相应的数组元素:

int y[4][3] = { // array of 4 arrays of 3 ints each (4x3 matrix)    { 1 },      // row 0 initialized to {1, 0, 0}    { 0, 1 },   // row 1 initialized to {0, 1, 0}    { [2]=1 },  // row 2 initialized to {0, 0, 1}};              // row 3 initialized to {0, 0, 0}

如果嵌套的初始化程序不是以大括号开头的话,那么只有列表中的足够的初始化程序可以用来解释子数组 struct struct 或 union 的元素或成员; 任何剩余的初始化器都将被初始化为下一个数组元素:

int y[4][3] = {    // array of 4 arrays of 3 ints each (4x2 matrix)1, 3, 5, 2, 4, 6, 3, 5, 7 // row 0 initialized to {1, 3, 5}};                        // row 1 initialized to {2, 4, 6}                          // row 2 initialized to {3, 5, 7}                          // row 3 initialized to {0, 0, 0}
 struct { int a[3], b; } w[] = { { 1 }, 2 }; // array of structs   // { 1 } is taken to be a fully-braced initializer for element #0 of the array   // that element is initialized to { {1, 0, 0}, 0}   // 2 is taken to be the first initialized for element #1 of the array   // that element is initialized { {2, 0, 0}, 0}

Array designators may be nested; the bracketed constant expression for nested arrays follows the bracketed constant expression for the outer array: int y4 = {0=1, 1=1, 2=1};  // row 0 initialized to {1, 0, 0}                                                // row 1 initialized to {0, 1, 0}                                                // row 2 initialized to {1, 0, 0}                                                // row 3 initialized to {0, 0, 0}

(since C99)

笔记

数组初始值设定项中子表达式的求值顺序在 C 中是不确定的(但在c ++ 11以后,不在 C ++中):

int n = 1;int a[2] = {n++, n++}; // unspecified, but well-defined behavior,                       // n is incremented twice (in arbitrary order)                       // a initialized to {1, 2} and to {2, 1} are both validputs((char[4]){'0'+n} + n++); // undefined behavior:                              // increment and read from n are unsequenced

在 C 中,初始化程序的支撑列表不能为空。C ++允许空列表:

int a[3] = {0}; // valid C and C++ way to zero-out a block-scope arrayint a[3] = {}; // invalid C but valid C++ way to zero-out a block-scope array

与所有其他初始化一样,初始化器列表中的每个表达式在初始化静态或线程本地存储持续时间数组时都必须是常量表达式:

static char* p[2] = {malloc(1), malloc(2)}; // error

int main(void){    // The following four array declarations are the same
    short q1[4][3][2] = {        { 1 },        { 2, 3 },        { 4, 5, 6 }    };
 
    short q2[4][3][2] = {1, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6};
 
    short q3[4][3][2] = {        {            { 1 },        },        {            { 2, 3 },        },        {            { 4, 5 },            { 6 },        }    };
 
    short q4[4][3][2] = {1, [1]=2, 3, [2]=4, 5, 6}; 
 
    // Character names can be associated with enumeration constants    // using arrays with designators:    enum { RED, GREEN, BLUE };    const char *nm[] = {        [RED] = "red",        [GREEN] = "green",        [BLUE] = "blue",    };}

参考

  • C11标准(ISO / IEC 9899:2011):

    • 6.7.9 / 12-38初始化(p:140-144)

  • C99标准(ISO / IEC 9899:1999):

    • 6.7.8 / 12-38初始化(p:126-130)

  • C89 / C90标准(ISO / IEC 9899:1990):

    • 3.5.7 / 12-初始化

上一篇:下一篇: