Can NULL be used in arrays in C?
In C language, NULL cannot be used directly in ordinary arrays, but can be cleverly used in pointer arrays: assign NULL to pointer array elements to indicate the end or invalid state of the array; when traversing pointer arrays, check whether the element is NULL to stop looping; when allocating pointer arrays, allocate more space to store NULL to avoid out-of-bounds access; when using NULL as the end flag of the array, pay attention to memory allocation and release to prevent memory leakage.
Can NULL be used in arrays in C? The answer is: it cannot be used directly, but it can be used cleverly.
This question seems simple, but it actually has a secret. Many beginners will take it for granted that since NULL
represents a null pointer and the array name is essentially a pointer, can't NULL
be assigned to an array? wrong! This idea ignores the subtle differences between arrays and pointers in C.
Let's review the basics first. In C, array names in most cases become pointers to their first element. However, the array name itself is not a pointer variable, it does not have independent storage space, and you cannot assign array names, for example array_name = NULL;
is illegal. NULL
is a macro, usually defined as (void *)0
, which represents a null pointer, pointing to memory address 0. Trying to assign NULL
to the array name is equivalent to trying to modify the start address of the array in memory, which is not allowed. The compiler will report an error directly.
So, is NULL
completely useless in array-related operations? Not so. We can use NULL
to represent the "end" or "invalid" state of an array. This usually occurs in scenarios where arrays are dynamically allocated or arrays of pointers are processed.
Imagine that you dynamically allocate an array of pointers to store some strings. If some strings are not assigned to, or you want to represent the end of the array, NULL
will come in handy.
Let’s take a look at an example:
<code class="c">#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char **string_array; // 指向字符串的指针数组int num_strings = 5; string_array = (char **)malloc(sizeof(char *) * (num_strings 1)); // 多分配一个空间用于NULL if (string_array == NULL) { fprintf(stderr, "内存分配失败!\n"); return 1; } // 初始化部分字符串string_array[0] = strdup("Hello"); string_array[1] = strdup("World"); string_array[2] = strdup("!"); string_array[3] = NULL; // 用NULL表示数组结束// 遍历并打印字符串int i = 0; while (string_array[i] != NULL) { printf("%s ", string_array[i]); free(string_array[i]); // 释放动态分配的内存i ; } printf("\n"); string_array[4] = strdup("This is a test"); // 使用剩余空间//再次遍历i = 0; while (string_array[i] != NULL) { printf("%s ", string_array[i]); free(string_array[i]); i ; } printf("\n"); free(string_array); // 释放指针数组本身的内存return 0; }</string.h></stdlib.h></stdio.h></code>
In this example, string_array
is an array of pointers to a string. We use NULL
as the sentinel value to mark the end of the array. When iterating through the array, we check if each element is NULL
to stop the loop. This is a common trick to avoid the hassle of needing additional maintenance of array lengths. Note that here we allocate one more element space than num_strings
, which is specifically used to store NULL
. Forgot this step is a common mistake, which may cause the program to access memory beyond the boundaries and cause crashes.
It should be noted that this method only applies to pointer arrays, not ordinary arrays. For ordinary arrays, NULL
is totally useless. Moreover, using NULL
as the array end flag requires careful processing of memory allocation and release, otherwise it is easy to cause memory leakage. Be sure to release the dynamically allocated memory in time after using it and develop good memory management habits. This is the only way to avoid C language memory problems.
The above is the detailed content of Can NULL be used in arrays in C?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WorldCoin (WLD) stands out in the cryptocurrency market with its unique biometric verification and privacy protection mechanisms, attracting the attention of many investors. WLD has performed outstandingly among altcoins with its innovative technologies, especially in combination with OpenAI artificial intelligence technology. But how will the digital assets behave in the next few years? Let's predict the future price of WLD together. The 2025 WLD price forecast is expected to achieve significant growth in WLD in 2025. Market analysis shows that the average WLD price may reach $1.31, with a maximum of $1.36. However, in a bear market, the price may fall to around $0.55. This growth expectation is mainly due to WorldCoin2.

The steps to draw a Bitcoin structure analysis chart include: 1. Determine the purpose and audience of the drawing, 2. Select the right tool, 3. Design the framework and fill in the core components, 4. Refer to the existing template. Complete steps ensure that the chart is accurate and easy to understand.

Exchanges that support cross-chain transactions: 1. Binance, 2. Uniswap, 3. SushiSwap, 4. Curve Finance, 5. Thorchain, 6. 1inch Exchange, 7. DLN Trade, these platforms support multi-chain asset transactions through various technologies.

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

In the bustling world of cryptocurrencies, new opportunities always emerge. At present, KernelDAO (KERNEL) airdrop activity is attracting much attention and attracting the attention of many investors. So, what is the origin of this project? What benefits can BNB Holder get from it? Don't worry, the following will reveal it one by one for you.

Aavenomics is a proposal to modify the AAVE protocol token and introduce token repos, which has implemented a quorum for AAVEDAO. Marc Zeller, founder of the AAVE Project Chain (ACI), announced this on X, noting that it marks a new era for the agreement. Marc Zeller, founder of the AAVE Chain Initiative (ACI), announced on X that the Aavenomics proposal includes modifying the AAVE protocol token and introducing token repos, has achieved a quorum for AAVEDAO. According to Zeller, this marks a new era for the agreement. AaveDao members voted overwhelmingly to support the proposal, which was 100 per week on Wednesday

In the volatile cryptocurrency market, investors are looking for alternatives that go beyond popular currencies. Although well-known cryptocurrencies such as Solana (SOL), Cardano (ADA), XRP and Dogecoin (DOGE) also face challenges such as market sentiment, regulatory uncertainty and scalability. However, a new emerging project, RexasFinance (RXS), is emerging. It does not rely on celebrity effects or hype, but focuses on combining real-world assets (RWA) with blockchain technology to provide investors with an innovative way to invest. This strategy makes it hoped to be one of the most successful projects of 2025. RexasFi

The platforms that have outstanding performance in leveraged trading, security and user experience in 2025 are: 1. OKX, suitable for high-frequency traders, providing up to 100 times leverage; 2. Binance, suitable for multi-currency traders around the world, providing 125 times high leverage; 3. Gate.io, suitable for professional derivatives players, providing 100 times leverage; 4. Bitget, suitable for novices and social traders, providing up to 100 times leverage; 5. Kraken, suitable for steady investors, providing 5 times leverage; 6. Bybit, suitable for altcoin explorers, providing 20 times leverage; 7. KuCoin, suitable for low-cost traders, providing 10 times leverage; 8. Bitfinex, suitable for senior play
