How to write an array literal in C (with explicit indexes)

How do you write a C array literal? The way I knew of was with curly braces:

This lists the array elements in order; i.e. at indexes 0, 1, then 2. But there is also a notation which uses explicit indexes. This program is the same:

But what happens when we use different indexes? All arrays must have indexes 0 to N with no gaps, since they are contiguous blocks of memory. So how does C choose the array length N? And what goes in the gaps? Let’s try it:

This prints:

C chooses the largest explicit index as the last index, and fills omitted indexes with zero values.

(Actually, I don’t know if the values are necessarily zeroes. They might be undefined.)

More by Jim

  • Your syntax highlighter is wrong
  • Granddad died today
  • The Three Ts of Time, Thought and Typing: measuring cost on the web
  • I hate telephones
  • The sorry state of OpenSSL usability
  • The dots do matter: how to scam a Gmail user
  • My parents are Flat-Earthers
  • How Hacker News stays interesting
  • Project C-43: the lost origins of asymmetric crypto
  • The hacker hype cycle
  • The inception bar: a new phishing method
  • Time is running out to catch COVID-19
  • A probabilistic pub quiz for nerds
  • Smear phishing: a new Android vulnerability

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.

c assign array literal

cppreference.com

Compound literals (since c99).

Constructs an unnamed object of specified type (which may be struct, union, or even array type) in-place.

[ edit ] Syntax

[ edit ] explanation.

The compound literal expression constructs an unnamed object of the type specified by type and initializes it as specified by initializer-list . Designated initializers are accepted.

The type of the compound literal is type (except when type is an array of unknown size; its size is deduced from the initializer-list as in array initialization ).

The value category of a compound literal is lvalue (its address can be taken).

[ edit ] Notes

Compound literals of const-qualified character or wide character array types may share storage with string literals .

Each compound literal creates only a single object in its scope:

Because compound literals are unnamed, a compound literal cannot reference itself (a named struct can include a pointer to itself)

Although the syntax of a compound literal is similar to a cast , the important distinction is that a cast is a non-lvalue expression while a compound literal is an lvalue.

[ edit ] Example

Possible output:

[ edit ] References

  • C23 standard (ISO/IEC 9899:2023):
  • 6.5.2.5 Compound literals (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.2.5 Compound literals (p: 61-63)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.2.5 Compound literals (p: 85-87)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.2.5 Compound literals (p: 75-77)
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 June 2023, at 10:10.
  • This page has been accessed 122,474 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Array of Strings in C

Use 2D Array Notation to Declare Array of Strings in C

Use the char* array notation to declare array of strings in c.

Array of Strings in C

This article will demonstrate multiple methods about how to declare an array of strings in C.

Strings in C are simply a sequence of chars stored in a contiguous memory region. One distinction about character strings is that there is a terminating null byte \0 stored at the end of the sequence, denoting one string’s end. If we declare a fixed array of char using the [] notation, then we can store a string consisting of the same number of characters in that location.

Note that one extra character space for the terminating null byte should be considered when copying the character string to the array location. Thus, one can declare a two-dimensional char array with brackets notation and utilize it as the array of strings.

The second dimension of the array will limit the maximum length of the string. In this case, we arbitrarily define a macro constant - MAX_LENGTH equal to 100 characters.

The whole array can be initialized with {""} notation, which zeros out each char element in the array.

When storing the string values in the already initialized array, the assignment operator is not permitted, and special memory copying functions should be employed like strcpy .

Alternatively, we can initialize the two-dimensional char array instantly when declared. The modern C11 standard allows to initialize char arrays with string literals and even store null byte at the end of the string automatically when the array length is larger than the string itself.

Initializer list notation is similar to the C++ syntax. Each curly braced element is supposed to be stored in a consecutive memory region of length MAX_LENGTH . In case the initializer notation specifies the fewer elements than the array size, the remaining elements are implicitly initialized with \0 bytes.

char* is the type that is generally used to store character strings. Declaring the array of char* gives us the fixed number of pointers pointing to the same number of character strings. It can be initialized with string literals as shown in the following example, assigned to or copied using special functions provided in the header string.h .

As an alternative, one can specify the {} braces only, which will initialize the pointers in the array to null , and they can be later used to stored other string addresses, or the programmer can even allocate dynamic memory.

Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article - C Array

  • How to Copy Char Array in C
  • How to Dynamically Allocate an Array in C
  • How to Clear Char Array in C
  • How to Initialize Char Array in C
  • How to Print Char Array in C

Related Article - C String

  • Null Terminated Strings in C
  • Scanf String With Spaces in C
  • How to Create Formatted Strings in C
  • How to Truncate String in C
  • How to Concatenate String and Int in C
  • How to Trim a String in C

C Programming Tutorial

  • Character Array and Character Pointer in C

Last updated on July 27, 2020

In this chapter, we will study the difference between character array and character pointer. Consider the following example:

Can you point out similarities or differences between them?

The similarity is:

The type of both the variables is a pointer to char or (char*) , so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer.

Here are the differences:

arr is an array of 12 characters. When compiler sees the statement:

c assign array literal

On the other hand when the compiler sees the statement.

It allocates 12 consecutive bytes for string literal "Hello World" and 4 extra bytes for pointer variable ptr . And assigns the address of the string literal to ptr . So, in this case, a total of 16 bytes are allocated.

c assign array literal

We already learned that name of the array is a constant pointer. So if arr points to the address 2000 , until the program ends it will always point to the address 2000 , we can't change its address. This means string assignment is not valid for strings defined as arrays.

On the contrary, ptr is a pointer variable of type char , so it can take any other address. As a result string, assignments are valid for pointers.

c assign array literal

After the above assignment, ptr points to the address of "Yellow World" which is stored somewhere in the memory.

Obviously, the question arises so how do we assign a different string to arr ?

We can assign a new string to arr by using gets() , scanf() , strcpy() or by assigning characters one by one.

Recall that modifying a string literal causes undefined behavior, so the following operations are invalid.

Using an uninitialized pointer may also lead to undefined undefined behavior.

Here ptr is uninitialized an contains garbage value. So the following operations are invalid.

We can only use ptr only if it points to a valid memory location.

Now all the operations mentioned above are valid. Another way we can use ptr is by allocation memory dynamically using malloc() or calloc() functions.

Let's conclude this chapter by creating dynamic 1-d array of characters.

Expected Output:

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants

C Data Types

  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

C Keywords and Identifiers

C Type Conversion

List of all Keywords in C Language

C Variables, Constants and Literals

In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name ( identifier ). Variable names are just the symbolic representation of a memory location. For example:

Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95 .

The value of a variable can be changed, hence the name variable.

Rules for naming a variable

  • A variable name can only have letters (both uppercase and lowercase letters), digits and underscore.
  • The first letter of a variable should be either a letter or an underscore.
  • There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.

Note: You should always try to give meaningful names to variables. For example: firstName is a better variable name than fn .

C is a strongly typed language. This means that the variable type cannot be changed once it is declared. For example:

Here, the type of number variable is int . You cannot assign a floating-point (decimal) value 5.5 to this variable. Also, you cannot redefine the data type of the variable to double . By the way, to store the decimal values in C, you need to declare its type to either double or float .

Visit this page to learn more about different types of data a variable can store .

Literals are data used for representing fixed values. They can be used directly in the code. For example: 1 , 2.5 , 'c' etc.

Here, 1 , 2.5 and 'c' are literals. Why? You cannot assign different values to these terms.

1. Integers

An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming:

  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

For example:

In C programming, octal starts with a 0 , and hexadecimal starts with a 0x .

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example:

Note: E-5 = 10 -5

3. Characters

A character literal is created by enclosing a single character inside single quotation marks. For example: 'a' , 'm' , 'F' , '2' , '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc.

In order to use these characters, escape sequences are used.

For example: \n is used for a newline. The backslash \ causes escape from the normal way the characters are handled by the compiler.

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For example:

If you want to define a variable whose value cannot be changed, you can use the  const keyword. This will create a constant. For example,

Notice, we have added keyword const .

Here, PI is a symbolic constant; its value cannot be changed.

You can also define a constant using the #define preprocessor directive. We will learn about it in  C Macros tutorial.

Table of Contents

  • Naming a Variable
  • Floating-point Numbers
  • Escape Sequences

Video: Variables in C Programming

Sorry about that.

Related Tutorials

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Related Articles

  • Solve Coding Problems
  • Properties of Array in C
  • Length of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Jagged Array or Array of Arrays in C with Examples
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • How to pass an array by value in C ?
  • Variable Length Arrays (VLAs) in C
  • What are the data types for which it is not possible to create an array?

Strings in C

  • Array of Strings in C
  • C Library - <string.h>
  • C String Functions
  • What is the difference between single quoted and double quoted declaration of char array?
  • Array C/C++ Programs
  • String C/C++ Programs

A String in C programming is a sequence of characters terminated with a null character ‘\0’. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character ‘\0’.

string in c

C String Declaration Syntax

Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.

In the above syntax string_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.

There is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of a string that differs strings from normal character arrays .

C String Initialization

A string in C can be initialized in different ways. We will explain this with the help of an example. Below are the examples to declare a string with the name str and initialize it with “GeeksforGeeks”.

We can initialize a C string in 4 different ways which are as follows:

1. Assigning a String Literal without Size

String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array.

2. Assigning a String Literal with a Predefined Size

String literals can be assigned with a predefined size. But we should always account for one extra space which will be assigned to the null character. If we want to store a string of size n then we should always declare a string with a size equal to or greater than n+1.

3. Assigning Character by Character with Size

We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a null character.

4. Assigning Character by Character without ize

We can assign character by character without size with the NULL character at the end. The size of the string is determined by the compiler automatically.

Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the compiler, a null character ‘\0’ is appended at the end of the string by default.

Let us now look at a sample program to get a clear understanding of declaring, and initializing a string in C, and also how to print a string with its size.

C String Example

We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character.

Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “ %s ” which can be used to print and read strings directly. 

Read a String Input From the User

The following example demonstrates how to take string input using scanf() function in C

You can see in the above program that the string can also be read using a single scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign with the string name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of scanf.  We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we are already providing the base address of the string to scanf.

Now consider one more example,

Here, the string is read only till the whitespace is encountered.

Note: After declaration, if we want to assign some other text to the string, we have to assign it one by one or use the built-in strcpy() function because the direct assignment of the string literal to character array is only possible in declaration.

How to Read a String Separated by Whitespaces in C?

We can use multiple methods to read a string separated by spaces in C. The two of the common ones are:

  • We can use the fgets() function to read a line of string and gets() to read characters from the standard input  (stdin) and store them as a C string until a newline character or the End-of-file (EOF) is reached.
  • We can also scanset characters inside the scanf() function

1. Example of String Input using gets()

2. example of string input using scanset, c string length.

The length of the string is the number of characters present in the string except for the NULL character. We can easily find the length of the string using the loop to count the characters from the start till the NULL character is found.

Passing Strings to Function

As strings are character arrays, we can pass strings to functions in the same way we pass an array to a function . Below is a sample program to do this: 

Note: We can’t read a string value with spaces, we can use either gets() or fgets() in the C programming language.

Strings and Pointers in C

In Arrays, the variable name points to the address of the first element.

Below is the memory representation of the string str = “Geeks”.

memory representation of strings

Similar to arrays, In C, we can create a character pointer to a string that points to the starting address of the string which is the first character of the string. The string can be accessed with the help of pointers as shown in the below example. 

Standard C Library – String.h  Functions

The C language comes bundled with <string.h> which contains some useful string-handling functions. Some of them are as follows:

  • puts() vs printf() to print a string
  • Swap strings in C
  • Storage for strings in C
  • gets() is risky to use!

Please Login to comment...

  • kamleshjoshi18
  • abhishekcpp
  • tanishabutola04

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • How to: literal string arrays...

  How to: literal string arrays...

c assign array literal

Declaration

A C string (also known as a null-terminated string is usually declared as an array of char . However, an array of char is not by itself a C string. A valid C string requires the presence of a terminating "null character" (a character with ASCII value 0, usually represented by the character literal '\0' ).

Since char is a built-in data type, no header file needs to be included to create a C string. The C library header file <cstring> contains a number of utility functions that operate on C strings.

Here are some examples of declaring C strings as arrays of char :

It is also possible to declare a C string as a pointer to a char :

This creates an unnamed character array just large enough to hold the string (including the null character) and places the address of the first element of the array in the char pointer s3 . This is a somewhat advanced method of manipulating C strings that should probably be avoided by inexperienced programmers who don't understand pointers yet. If used improperly, it can easily result in corrupted program memory or runtime errors.

Representation in Memory

Here is another example of declaring a C string:

The following diagram shows how the string name is represented in memory:

The individual characters that make up the string are stored in the elements of the array. The string is terminated by a null character. Array elements after the null character are not part of the string, and their contents are irrelevant.

A "null string" or "empty string" is a string with a null character as its first character:

The length of a null string is 0.

What about a C string declared as a char pointer?

This declaration creates an unnamed character array just large enough to hold the string "Karen" (including room for the null character) and places the address of the first element of the array in the char pointer name :

Subscripting

Like any other array, the subscript operator may be used to access the individual characters of a C++ string:

Since the name of a C string is converted to a pointer to a char when used in a value context, you can also use pointer notation to access the characters of the string:

String Length

You can obtain the length of a C string using the C library function strlen() . This function takes a character pointer that points to a C string as an argument. It returns the data type size_t (a data type defined as some form of unsigned integer), the number of valid characters in the string (not including the null character).

String Comparison

Comparing C strings using the relational operators == , != , > , < , >= , and <= does not work correctly, since the array names will be converted to pointers. For example, the expression

actually compares the addresses of the first elements of the arrays s1 and s2 , not their contents. Since those addresses are different, the relational expression is always false.

To compare the contents of two C strings, you should use the C library function strcmp() . This function takes two pointers to C strings as arguments, either or both of which can be string literals. It returns an integer less than, equal to, or greater than zero if the first argument is found, respectively, to be less than, to match, or be greater than the second argument.

The strcmp() function can be used to implement various relational expressions:

A character array (including a C string) can not have a new value assigned to it after it is declared.

To change the contents of a character array, use the C library function strcpy() . This function takes two arguments: 1) a pointer to a destination array of characters that is large enough to hold the entire copied string (including the null character), and 2) a pointer to a valid C string or a string literal. The function returns a pointer to the destination array, although this return value is frequently ignored.

If the string specified by the second argument is larger than the character array specified by the first argument, the string will overflow the array, corrupting memory or causing a runtime error.

Input and Output

The stream extraction operator >> may be used to read data into a character array as a C string. If the data read contains more characters than the array can hold, the string will overflow the array.

The stream insertion operator << may be used to print a C string or string literal.

Concatenation

The C library function strcat() can be used to concatenate C strings. This function takes two arguments: 1) a pointer to a destination character array that contains a valid C string, and 2) a pointer to a valid C string or string literal. The function returns a pointer to the destination array, although this return value is frequently ignored.

The destination array must be large enough to hold the combined strings (including the null character). If it is not, the array will overflow.

Passing and returning

Regardless of how a C string is declared, when you pass the string to a function or return it from a function, the data type of the string can be specified as either char[] (array of char ) or char* (pointer to char ). In both cases, the string is passed or returned by address .

A string literal like "hello" is considered a constant C string, and typically has its data type specified as const char* (pointer to a char constant).

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Arrays (C++)

  • 8 contributors

An array is a sequence of objects of the same type that occupy a contiguous area of memory. Traditional C-style arrays are the source of many bugs, but are still common, especially in older code bases. In modern C++, we strongly recommend using std::vector or std::array instead of C-style arrays described in this section. Both of these standard library types store their elements as a contiguous block of memory. However, they provide greater type safety, and support iterators that are guaranteed to point to a valid location within the sequence. For more information, see Containers .

Stack declarations

In a C++ array declaration, the array size is specified after the variable name, not after the type name as in some other languages. The following example declares an array of 1000 doubles to be allocated on the stack. The number of elements must be supplied as an integer literal or else as a constant expression. That's because the compiler has to know how much stack space to allocate; it can't use a value computed at run-time. Each element in the array is assigned a default value of 0. If you don't assign a default value, each element initially contains whatever random values happen to be at that memory location.

The first element in the array is the zeroth element. The last element is the ( n -1) element, where n is the number of elements the array can contain. The number of elements in the declaration must be of an integral type and must be greater than 0. It is your responsibility to ensure that your program never passes a value to the subscript operator that is greater than (size - 1) .

A zero-sized array is legal only when the array is the last field in a struct or union and when the Microsoft extensions are enabled ( /Za or /permissive- isn't set).

Stack-based arrays are faster to allocate and access than heap-based arrays. However, stack space is limited. The number of array elements can't be so large that it uses up too much stack memory. How much is too much depends on your program. You can use profiling tools to determine whether an array is too large.

Heap declarations

You may require an array that's too large to allocate on the stack, or whose size isn't known at compile time. It's possible to allocate this array on the heap by using a new[] expression. The operator returns a pointer to the first element. The subscript operator works on the pointer variable the same way it does on a stack-based array. You can also use pointer arithmetic to move the pointer to any arbitrary elements in the array. It's your responsibility to ensure that:

  • you always keep a copy of the original pointer address so that you can delete the memory when you no longer need the array.
  • you don't increment or decrement the pointer address past the array bounds.

The following example shows how to define an array on the heap at run time. It shows how to access the array elements using the subscript operator and by using pointer arithmetic:

Initializing arrays

You can initialize an array in a loop, one element at a time, or in a single statement. The contents of the following two arrays are identical:

Passing arrays to functions

When an array is passed to a function, it's passed as a pointer to the first element, whether it's a stack-based or heap-based array. The pointer contains no other size or type information. This behavior is called pointer decay . When you pass an array to a function, you must always specify the number of elements in a separate parameter. This behavior also implies that the array elements aren't copied when the array gets passed to a function. To prevent the function from modifying the elements, specify the parameter as a pointer to const elements.

The following example shows a function that accepts an array and a length. The pointer points to the original array, not a copy. Because the parameter isn't const , the function can modify the array elements.

Declare and define the array parameter p as const to make it read-only within the function block:

The same function can also be declared in these ways, with no change in behavior. The array is still passed as a pointer to the first element:

Multidimensional arrays

Arrays constructed from other arrays are multidimensional arrays. These multidimensional arrays are specified by placing multiple bracketed constant expressions in sequence. For example, consider this declaration:

It specifies an array of type int , conceptually arranged in a two-dimensional matrix of five rows and seven columns, as shown in the following figure:

The image is a grid 7 cells wide and 5 cells high. Each cell contains the index of the cell. The first cell index is labeled 0,0. The next cell in that row is 0,1 and so on to the last cell in that row which is 0,6. The next row starts with the index 1,0. The cell after that has an index of 1,1. The last cell in that row is 1,6. This pattern repeats until the last row, which starts with the index 4,0. The last cell in the last row has an index of 4,6. :::image-end

You can declare multidimensioned arrays that have an initializer list (as described in Initializers ). In these declarations, the constant expression that specifies the bounds for the first dimension can be omitted. For example:

The preceding declaration defines an array that is three rows by four columns. The rows represent factories and the columns represent markets to which the factories ship. The values are the transportation costs from the factories to the markets. The first dimension of the array is left out, but the compiler fills it in by examining the initializer.

Use of the indirection operator (*) on an n-dimensional array type yields an n-1 dimensional array. If n is 1, a scalar (or array element) is yielded.

C++ arrays are stored in row-major order. Row-major order means the last subscript varies the fastest.

You can also omit the bounds specification for the first dimension of a multidimensional array in function declarations, as shown here:

The function FindMinToMkt is written such that adding new factories doesn't require any code changes, just a recompilation.

Initializing Arrays

Arrays of objects that have a class constructor are initialized by the constructor. When there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete , that is, there must be one initializer for each element in the array.

Consider the Point class that defines two constructors:

The first element of aPoint is constructed using the constructor Point( int, int ) ; the remaining two elements are constructed using the default constructor.

Static member arrays (whether const or not) can be initialized in their definitions (outside the class declaration). For example:

Accessing array elements

You can access individual elements of an array by using the array subscript operator ( [ ] ). If you use the name of a one-dimensional array without a subscript, it gets evaluated as a pointer to the array's first element.

When you use multidimensional arrays, you can use various combinations in expressions.

In the preceding code, multi is a three-dimensional array of type double . The p2multi pointer points to an array of type double of size three. In this example, the array is used with one, two, and three subscripts. Although it's more common to specify all subscripts, as in the cout statement, sometimes it's useful to select a specific subset of array elements, as shown in the statements that follow cout .

Overloading subscript operator

Like other operators, the subscript operator ( [] ) can be redefined by the user. The default behavior of the subscript operator, if not overloaded, is to combine the array name and the subscript using the following method:

*((array_name) + (subscript))

As in all addition that involves pointer types, scaling is done automatically to adjust for the size of the type. The resultant value isn't n bytes from the origin of array_name ; instead, it's the n th element of the array. For more information about this conversion, see Additive operators .

Similarly, for multidimensional arrays, the address is derived using the following method:

((array_name) + (subscript1 * max2 * max3 * ... * maxn) + (subscript2 * max3 * ... * maxn) + ... + subscriptn))

Arrays in Expressions

When an identifier of an array type appears in an expression other than sizeof , address-of ( & ), or initialization of a reference, it's converted to a pointer to the first array element. For example:

The pointer psz points to the first element of the array szError1 . Arrays, unlike pointers, aren't modifiable l-values. That's why the following assignment is illegal:

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

IMAGES

  1. Arrays in C#

    c assign array literal

  2. Trinity

    c assign array literal

  3. Array of Strings in C Detailed Explanation Made Easy Lec-70

    c assign array literal

  4. String In Char Array VS. Pointer To String Literal

    c assign array literal

  5. C Arrays

    c assign array literal

  6. Mastering Swift: Tips About Array and Dictionary Literals

    c assign array literal

VIDEO

  1. Assign array elements from user input

  2. 3D render of a rotating the beam in a circular phased array

  3. Array of Structures in C Programming Language Video tutorial

  4. Array : Can't assign string to pointer inside struct

  5. C++ : Cannot assign element std::array directly, it says no operator "=" matches

  6. Arrays in C++

COMMENTS

  1. Literal array in C

    20 This question already has answers here : How to pass a constant array literal to a function that takes a pointer without using a variable C/C++? (12 answers) Closed 10 years ago. I may be wrong in my definition of what a literal array is. I am refering to the following as one: {0x00, 0x01, 0x03}

  2. Array initialization

    When initializing an object of array type, the initializer must be either a string literal (optionally enclosed in braces) or be a brace-enclosed list of initialized for array members: string-literal ={expression,...} (until C99) ={designator(optional)expression,...} (since C99) } (since C23)

  3. Arrays

    Article 09/01/2023 1 contributor Feedback In this article Single-dimensional arrays Multidimensional arrays Jagged arrays Implicitly typed arrays You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements.

  4. How to Initialize Char Array in C

    HowTo C Howtos How to Initialize Char Array in C Jinku Hu Feb 02, 2024 C C Array Use {} Curly Braced List Notation to Initialize a char Array in C Use String Assignment to Initialize a char Array in C Use { { }} Double Curly Braces to Initialize 2D char Array in C

  5. How to write an array literal in C (with explicit indexes)

    How do you write a C array literal? The way I knew of was with curly braces: #include <stdio.h> int main () { char* strs [] = { "foo", "bar", "baz" }; for (size_t i = 0; i < sizeof (strs)/sizeof (strs [0]); i++) printf ("strs [%zu] = %s\n", i, strs [i]); return 0; } % ./a.out strs [0] = foo strs [1] = bar strs [2] = baz

  6. Array declaration

    Array is a type consisting of a contiguously allocated nonempty sequence of objects with a particular element type. The number of those objects (the array size) never changes during the array lifetime. Syntax

  7. c

    Here is the reply: It's anyways bad practice to initialie a char array with a string literal. So always do one of the following: const char string1[] = "october"; char string2[20]; strcpy(string2, "september"); c programming-practices strings array Share Improve this question edited May 18, 2015 at 9:05 Pacerier 4,993 7 39 59

  8. Compound literals (since C99)

    The compound literal expression constructs an unnamed object of the type specified by type and initializes it as specified by initializer-list. Designated initializers are accepted. The type of the compound literal is type (except when type is an array of unknown size; its size is deduced from the initializer-list as in array initialization ).

  9. C Arrays (With Examples)

    Arrays in C An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data[100]; How to declare an array? dataType arrayName[arraySize]; For example, float mark[5]; Here, we declared an array, mark, of floating-point type. And its size is 5.

  10. Array of Strings in C

    Use the char* Array Notation to Declare Array of Strings in C. char* is the type that is generally used to store character strings. Declaring the array of char* gives us the fixed number of pointers pointing to the same number of character strings. It can be initialized with string literals as shown in the following example, assigned to or copied using special functions provided in the header ...

  11. Character Array and Character Pointer in C

    It allocates 12 consecutive bytes for string literal "Hello World" and 4 extra bytes for pointer variable ptr.And assigns the address of the string literal to ptr.So, in this case, a total of 16 bytes are allocated.. We already learned that name of the array is a constant pointer.

  12. C Variables, Constants and Literals

    An integer is a numeric literal (associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming: decimal (base 10) octal (base 8) hexadecimal (base 16) For example: Decimal: 0, -9, 22 etc Octal: 021, 077, 033 etc Hexadecimal: 0x7f, 0x2a, 0x521 etc.

  13. Literals in C

    In C, Literals are the Constant values that are assigned to the constant variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, "const int = 5;", is a constant expression ...

  14. Strings in C

    1. Assigning a String Literal without Size String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array. char str [] = "GeeksforGeeks"; 2. Assigning a String Literal with a Predefined Size String literals can be assigned with a predefined size.

  15. How to: literal string arrays...

    And you can iterate through this array using standard C++ functions sttd::begin and std::end. By the way if I am not mistaken (everybody can check this himself) every object of type std::string occupies 16 bytes in MS VC++ do not taking into account the memory allocated dynamically for storing string literals.

  16. C Strings

    C Strings. A C string (also known as a null-terminated string is usually declared as an array of . However, an array of not by itself a C string. A valid C string requires the presence of a terminating "null character" (a character with ASCII value 0, usually represented by the character literal '\0' ). is a built-in data type, no header file ...

  17. assign a char array to a literal string

    assign a char array to a literal string - c++ Ask Question Asked 11 years, 9 months ago Modified 11 years, 9 months ago Viewed 3k times 5 char arr[3]; arr="hi";// ERROR cin>>arr;// and at runtime I type hi, which works fine. 1)can someone explain to me why?

  18. Arrays (C++)

    Show 7 more. An array is a sequence of objects of the same type that occupy a contiguous area of memory. Traditional C-style arrays are the source of many bugs, but are still common, especially in older code bases. In modern C++, we strongly recommend using std::vector or std::array instead of C-style arrays described in this section.

  19. How to return an array literal in C#

    It's also worth nothing that C# doesn't actually have array literals, but an array initialization syntax - to which the accepted answer refers. Literals are special in that they can be directly serialized, and can be assigned to const fields. This is not the case with array initialization syntax. - cwharris Dec 9, 2016 at 21:40 Add a comment