• How to Initialize Char Array in C

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.

How to Initialize Char Array in C

This article will demonstrate multiple methods of how to initialize a char array in C.

A char array is mostly declared as a fixed-sized structure and often initialized immediately. Curly braced list notation is one of the available methods to initialize the char array with constant values.

It’s possible to specify only the portion of the elements in the curly braces as the remainder of chars is implicitly initialized with a null byte value.

It can be useful if the char array needs to be printed as a character string. Since there’s a null byte character guaranteed to be stored at the end of valid characters, then the printf function can be efficiently utilized with the %s format string specifier to output the array’s content.

Another useful method to initialize a char array is to assign a string value in the declaration statement. The string literal should have fewer characters than the length of the array; otherwise, there will be only part of the string stored and no terminating null character at the end of the buffer.

Thus, if the user will try to print the array’s content with the %s specifier, it might access the memory region after the last character and probably will throw a fault.

Note that c_arr has a length of 21 characters and is initialized with a 20 char long string. As a result, the 21st character in the array is guaranteed to be \0 byte, making the contents a valid character string.

The curly braced list can also be utilized to initialize two-dimensional char arrays. In this case, we declare a 5x5 char array and include five braced strings inside the outer curly braces.

Note that each string literal in this example initializes the five-element rows of the matrix. The content of this two-dimensional array can’t be printed with %s specifier as the length of each row matches the length of the string literals; thus, there’s no terminating null byte stored implicitly during the initialization. Usually, the compiler will warn if the string literals are larger than the array rows.

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
  • Array of Strings in C
  • How to Print Char Array in C
  • Overview of C
  • Features of C
  • Install C Compiler/IDE
  • My First C program
  • Compile and Run C program
  • Understand Compilation Process

C Syntax Rules

  • Keywords and Identifier
  • Understanding Datatypes
  • Using Datatypes (Examples)
  • What are Variables?
  • What are Literals?
  • Constant value Variables - const
  • C Input / Output
  • Operators in C Language
  • Decision Making
  • Switch Statement
  • String and Character array
  • Storage classes

C Functions

  • Introduction to Functions
  • Types of Functions and Recursion
  • Types of Function calls
  • Passing Array to function

C Structures

  • All about Structures
  • Pointers concept
  • Declaring and initializing pointer
  • Pointer to Pointer
  • Pointer to Array
  • Pointer to Structure
  • Pointer Arithmetic
  • Pointer with Functions

C File/Error

  • File Input / Output
  • Error Handling
  • Dynamic memory allocation
  • Command line argument
  • 100+ C Programs with explanation and output

String and Character Array

String is a sequence of characters that are treated as a single data item and terminated by a null character '\0' . Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.

If you don't know what an array in C means, you can check the C Array tutorial to know about Array in the C language. Before proceeding further, check the following articles:

C Function Calls

C Variables

C Datatypes

For example: The string "home" contains 5 characters including the '\0' character which is automatically added by the compiler at the end of the string.

string in C

Declaring and Initializing a string variables:

String input and output:.

%s format specifier to read a string input from the terminal.

But scanf() function, terminates its input on the first white space it encounters.

edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.

The gets() function can also be used to read character string with white spaces

String Handling Functions:

C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h header file in your programs to use these functions.

The following are the most commonly used string handling functions.

strcat() function in C:

strcat() function in C

strcat() will add the string "world" to "hello" i.e ouput = helloworld.

strlen() and strcmp() function:

strlen() will return the length of the string passed to it and strcmp() will return the ASCII difference between first unmatching character of two strings.

strcpy() function:

It copies the second string argument to the first string argument.

srtcpy() function in C

Example of strcpy() function:

StudyTonight

strrev() function:

It is used to reverse the given string expression.

strrev() function in C

Code snippet for strrev() :

Enter your string: studytonight Your reverse string is: thginotyduts

Related Tutorials:

  • ← Prev
  • Next →

What is Character Array in C?

C++ Course: Learn the Essentials

  • A Character array is a derived data type in C that is used to store a collection of characters or strings.
  • A char data type takes 1 byte of memory, so a character array has the memory of the number of elements in the array. (1* number_of_elements_in_array) .
  • Each character in a character array has an index that shows the position of the character in the string.
  • The first character will be indexed 0 and the successive characters are indexed 1,2,3 etc...
  • The null character \0 is used to find the end of characters in the array and is always stored in the index after the last character or in the last index.

Consider a string "character", it is indexed as the following image in a character array.

character-in-character-array

There are many syntaxes for creating a character array in c. The most basic syntax is,

  • The name depicts the name of the character array and size is the length of the character array.
  • The size can be greater than the length of the string but can not be lesser. If it is lesser then the full string can't be stored and if it is greater the remaining spaces are just left unused.

Before seeing the example, let us understand the method of dynamic memory allocation which is used to create the dynamic array.

  • Dynamic memory allocation is an efficient way to allocate memory for a variable in c.
  • The memory is allocated in the runtime after getting the number of characters from the user.
  • It uses pointers, which are structures that point to an address where the real value of the variable is stored.
  • The malloc() function is used for dynamic memory allocation. Its syntax is,
  • The malloc function returns a void pointer which is cast (converted) to the required data type.
  • The sizeof() function gives the size of data types and has the syntax,
  • The malloc method is present in the header stdlib.h .

Now, let us see the example of how we can create a dynamic single-dimension character array by getting input from the user.

Anyone may find this line in code curious,

There is no & in scanf. This is because the variable arr is a pointer that points to an address and the & symbol is used to represent the address at which the variable is stored.

The space before %c is left intentionally and by doing this the scanf() function skips reading white spaces.

The arr+i is used to store the values in consecutive addresses with a difference of 4 bytes(size of a pointer) which is diagrammatically expressed below,

access-of-address-in-dynamic-memory

Initialization of Character Array in C

There are different ways to initialize a character array in c. Let us understand them with examples.

Using {} Curly Braces

  • We can use {} brackets to initialize a character array by specifying the characters in the array.
  • The advantage of using this method is we don't have to specify the length of the array as the compiler can find it for us.

Let us see a example where we initialize an array using {} and print it.

The puts() function is used to print a character array or string to the output. It has the following syntax

The const char* is a character pointer that points to the character array. The puts function returns a positive integer on success and the EOF(End of file) error on failure.

The strlen() function is present in the string.h header and is used to find the length of a string. It has the following syntax,

This function returns the length of the string.

Using String Assignment

  • A easy way to initialize a character array is using string assignment.
  • We don't need to specify the length of the array in this method too.

Consider the following example,

Using {{ }} Double Curly Braces(2D Char Array)

  • This method is used to store two or more strings together in a single array.
  • As a character array can only store characters, to store different strings we use a 2-dimensional array with syntax arr[i][j] .
  • The i denotes the string and j denote the position of the character in the string at position i.
  • The i can be left empty as it is automatically computed by the compiler but the value of j must be provided.

Examples of Character Array in C

Let us see more examples to better understand character arrays.

Convert Integers to Characters

  • In computers, characters are represented as numbers according to the ASCII values .
  • The ASCII value can represent numbers from 0-9, alphabets(both lower and upper case), and some special characters. The ASCII values are predefined for each letter or character.
  • To convert an integer to a character we add the integer with 0 , which has an ASCII value of 48. For example, If we want the letter A which has an ASCII value of 65, we just need to add 0 and 17.
  • From the input number, we take the last digit and convert it to a character then store it, then follow the same for the rest of the digits by removing the digit as it is converted to a character and stored.

Convert Multiple Arrays to Character Array

  • We can concatenate multiple arrays to a single array using loops to iterate till \0 to find the last element of the first array.
  • Then add the elements of the second array to the end of the first array.
  • Then we mark the end of the array with \0 .
  • In this example we have used %s which is the data type for a string in c.

Convert Strings to Character Array

  • We can concat many strings to a character vector using the strcat() method in c.
  • The syntax of strcat() method is ,
  • This method concatenates two strings and stores the result in string1.
  • This method is present in the header string.h .
  • The strlen() method returns the length of the string and has the syntax,
  • This method is also present in the string.h header.

In this example, we are concating two arrays using the strcat function and printing the concatenated string.

Convert Duration Array to Character Array

  • The scanf() not only reads input but also returns how many inputs are read.
  • It has some special syntax to perform special functions such as the %n representing that only n numbers are read.
  • The [^symbol] represents that the symbol is excluded when reading the input.

We first read 2 digits for hours and 2 digits for minutes while excluding the character : . We store the values in character arrays h and m.

What is the Use of Char Array in C?

  • A string is stored and represented using a character array.
  • Every string operation such as copying two strings or concatenating two strings is done only using the character array.
  • We can individually access every character in an array using the character array.
  • Writing and reading from files also use character arrays.

Importance of Char Array

  • Character array is used to store and manipulate characters.
  • File systems and text editors use character arrays to manipulate strings.
  • NoSQL(Not only SQL) databases that store data in JSON also use character arrays.
  • Character array is used in language processing software and speech-to-text software.
  • It is used in DNA matching and genome matching as pattern matching can be easily done using characters.

Program for Char Array in C

Display a given string through the use of char array in c programming.

  • The gets() function can be used to get the string as input from the user.It receives input from the user until the Enter key is pressed. It has the following syntax,

The gets function returns the arr on successfully getting input from user or returns EOF(error on failure) .

In this program, we are getting the string from the user and storing it in the array arr . Then we check if the array is empty by checking the first position of the array for \0 . If the array is not empty, then we print the elements of the array.

Program in C to Calculate the Length and Size of a Given String

  • The string length and size can be easily computed by the strlen() method and using the sizeof() operator.
  • The size of the string is the same as the length of the string because the size of char is 1. The total size of the string is 1*length_of_string .
  • The string length can also be calculated without using the strlen() method. We will look into both methods with the following example,

We have created a for loop which will increment the value of i till the end of the string is reached. Finally, the value of i will be the length of the string.

Similarities & Differences between Character Array and Character Pointer in C

The differences between the character array and pointer are listed below,

  • A character pointer is a pointer that stores the address of the character array. It represents the address of the character array.
  • A character array is used to store the character and represent the values in the character array. The way of defining the character pointer and the array is,
  • In character pointer the values at each index can be accessed by adding the pointer and the location at which the value is present.
  • In the character array the values at each index can be accessed by the index.

The * used here is called the dereferencing operator and is used to get the value from the address stored in ptr+2.

  • The value of the character array can't be replaced as the old address can't be changed.
  • The value of the address pointer can be changed as it can change its address and point to the new array.
  • Dynamic memory allocation can't be used in the character array.
  • Dynamic memory allocation can be used in character pointers.

The similarity between character array and pointer is,

  • Both the character array and character pointer have a data type of char or char * which makes them similar to be handled by any function.

Difference Between Character Array and String

  • Character array represents a series of characters that are indexed separately and stored consecutively in memory.
  • String are characters written together, they can also be represented as a character array.
  • A string should be assigned to a character array at the time of initialization or else an error will occur.
  • The above example proves that strings are not the same as characters but both string and character array are interchangeable.
  • Character arrays in C are used to store characters and represent strings.
  • There are three ways to initialize a character array.
  • Character array can be manipulated by using functions such as strlen() and strcat() etc..
  • Character arrays are very useful and have important use cases.
  • There are many similarities and differences between the character Array and the character Pointer in C.
  • There are a few aspects in which a Character Array differs from a String.

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:

char array assignment in c

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.

char array assignment in c

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.

char array assignment in c

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

C String – How to Declare Strings in the C Programming Language

Dionysia Lemonaki

Computers store and process all kinds of data.

Strings are just one of the many forms in which information is presented and gets processed by computers.

Strings in the C programming language work differently than in other modern programming languages.

In this article, you'll learn how to declare strings in C.

Before doing so, you'll go through a basic overview of what data types, variables, and arrays are in C. This way, you'll understand how these are all connected to one another when it comes to working with strings in C.

Knowing the basics of those concepts will then help you better understand how to declare and work with strings in C.

Let's get started!

Data types in C

C has a few built-in data types.

They are int , short , long , float , double , long double and char .

As you see, there is no built-in string or str (short for string) data type.

The char data type in C

From those types you just saw, the only way to use and present characters in C is by using the char data type.

Using char , you are able to to represent a single character – out of the 256 that your computer recognises. It is most commonly used to represent the characters from the ASCII chart.

The single characters are surrounded by single quotation marks .

The examples below are all char s – even a number surrounded by single quoation marks and a single space is a char in C:

Every single letter, symbol, number and space surrounded by single quotation marks is a single piece of character data in C.

What if you want to present more than one single character?

The following is not a valid char – despite being surrounded by single quotation marks. This is because it doesn't include only a single character inside the single quotation marks:

'freeCodeCamp is awesome'

When many single characters are strung together in a group, like the sentence you see above, a string is created. In that case, when you are using strings, instead of single quotation marks you should only use double quotation marks.

"freeCodeCamp is awesome"

How to declare variables in C

So far you've seen how text is presented in C.

What happens, though, if you want to store text somewhere? After all, computers are really good at saving information to memory for later retrieval and use.

The way you store data in C, and in most programming languages, is in variables.

Essentially, you can think of variables as boxes that hold a value which can change throughout the life of a program. Variables allocate space in the computer's memory and let C know that you want some space reserved.

C is a statically typed language, meaning that when you create a variable you have to specify what data type that variable will be.

There are many different variable types in C, since there are many different kinds of data.

Every variable has an associated data type.

When you create a variable, you first mention the type of the variable (wether it will hold integer, float, char or any other data values), its name, and then optionally, assign it a value:

Be careful not to mix data types when working with variables in C, as that will cause errors.

For intance, if you try to change the example from above to use double quotation marks (remember that chars only use single quotation marks), you'll get an error when you compile the code:

As mentioned earlier on, C doesn't have a built-in string data type. That also means that C doesn't have string variables!

How to create arrays in C

An array is essentially a variable that stores multiple values. It's a collection of many items of the same type.

As with regular variables, there are many different types of arrays because arrays can hold only items of the same data type. There are arrays that hold only int s, only float s, and so on.

This is how you define an array of ints s for example:

First you specify the data type of the items the array will hold. Then you give it a name and immediately after the name you also include a pair of square brackets with an integer. The integer number speficies the length of the array.

In the example above, the array can hold 3 values.

After defining the array, you can assign values individually, with square bracket notation, using indexing. Indexing in C (and most programming languages) starts at 0 .

You reference and fetch an item from an array by using the name of the array and the item's index in square brackets, like so:

What are character arrays in C?

So, how does everything mentioned so far fit together, and what does it have to do with initializing strings in C and saving them to memory?

Well, strings in C are actually a type of array – specifically, they are a character array . Strings are a collection of char values.

How strings work in C

In C, all strings end in a 0 . That 0 lets C know where a string ends.

That string-terminating zero is called a string terminator . You may also see the term null zero used for this, which has the same meaning.

Don't confuse this final zero with the numeric integer 0 or even the character '0' - they are not the same thing.

The string terminator is added automatically at the end of each string in C. But it is not visible to us – it's just always there.

The string terminator is represented like this: '\0' . What sets it apart from the character '0' is the backslash it has.

When working with strings in C, it's helpful to picture them always ending in null zero and having that extra byte at the end.

Screenshot-2021-10-04-at-8.46.08-PM

Each character takes up one byte in memory.

The string "hello" , in the picture above, takes up 6 bytes .

"Hello" has five letters, each one taking up 1 byte of space, and then the null zero takes up one byte also.

The length of strings in C

The length of a string in C is just the number of characters in a word, without including the string terminator (despite it always being used to terminate strings).

The string terminator is not accounted for when you want to find the length of a string.

For example, the string freeCodeCamp has a length of 12 characters.

But when counting the length of a string, you must always count any blank spaces too.

For example, the string I code has a length of 6 characters. I is 1 character, code has 4 characters, and then there is 1 blank space.

So the length of a string is not the same number as the number of bytes that it has and the amount of memory space it takes up.

How to create character arrays and initialize strings in C

The first step is to use the char data type. This lets C know that you want to create an array that will hold characters.

Then you give the array a name, and immediatelly after that you include a pair of opening and closing square brackets.

Inside the square brackets you'll include an integer. This integer will be the largest number of characters you want your string to be including the string terminator.

You can initialise a string one character at a time like so:

But this is quite time-consuming. Instead, when you first define the character array, you have the option to assign it a value directly using a string literal in double quotes:

If you want, istead of including the number in the square brackets, you can only assign the character array a value.

It works exactly the same as the example above. It will count the number of characters in the value you provide and automatically add the null zero character at the end:

Remember, you always need to reserve enough space for the longest string you want to include plus the string terminator.

If you want more room, need more memory, and plan on changing the value later on, include a larger number in the square brackets:

How to change the contents of a character array

So, you know how to initialize strings in C. What if you want to change that string though?

You cannot simply use the assignment operator ( = ) and assign it a new value. You can only do that when you first define the character array.

As seen earlier on, the way to access an item from an array is by referencing the array's name and the item's index number.

So to change a string, you can change each character individually, one by one:

That method is quite cumbersome, time-consuming, and error-prone, though. It definitely is not the preferred way.

You can instead use the strcpy() function, which stands for string copy .

To use this function, you have to include the #include <string.h> line after the #include <stdio.h> line at the top of your file.

The <string.h> file offers the strcpy() function.

When using strcpy() , you first include the name of the character array and then the new value you want to assign. The strcpy() function automatically add the string terminator on the new string that is created:

And there you have it. Now you know how to declare strings in C.

To summarize:

  • C does not have a built-in string function.
  • To work with strings, you have to use character arrays.
  • When creating character arrays, leave enough space for the longest string you'll want to store plus account for the string terminator that is included at the end of each string in C.
  • Define the array and then assign each individual character element one at a time.
  • OR define the array and initialize a value at the same time.
  • When changing the value of the string, you can use the strcpy() function after you've included the <string.h> header file.

If you want to learn more about C, I've written a guide for beginners taking their first steps in the language.

It is based on the first couple of weeks of CS50's Introduction to Computer Science course and I explain some fundamental concepts and go over how the language works at a high level.

You can also watch the C Programming Tutorial for Beginners on freeCodeCamp's YouTube channel.

Thanks for reading and happy learning :)

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program
  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

Programming Arrays

C Multidimensional Arrays

Pass arrays to a function in C

Programming Pointers

Relationship Between Arrays and Pointers

  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples

Programming Strings

  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

Structure and Union

  • C structs and Pointers
  • C Structure and Function

Programming Files

  • C File Handling

C Files Examples

Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions
  • Find Largest Element in an Array
  • Calculate Average Using Arrays
  • Access Array Elements Using Pointer
  • Add Two Matrices Using Multi-dimensional Arrays

C arrays

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.

How to declare an array?

For example,

Here, we declared an array, mark , of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0] , the second element is mark[1] and so on.

C Array declaration

Few keynotes :

  • Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
  • If the size of an array is n , to access the last element, the n-1 index is used. In this example, mark[4]
  • Suppose the starting address of mark[0] is 2120d . Then, the address of the mark[1] will be 2124d . Similarly, the address of mark[2] will be 2128d and so on. This is because the size of a float is 4 bytes.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

You can also initialize an array like this.

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Initialize an array in C programming

Change Value of Array elements

Input and output array elements.

Here's how you can take input from the user and store it in an array element.

Here's how you can print an individual element of an array.

Example 1: Array Input/Output

Here, we have used a  for loop to take 5 inputs from the user and store them in an array. Then, using another  for loop, these elements are displayed on the screen.

Example 2: Calculate Average

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

You can access the array elements from testArray[0] to testArray[9] .

Now let's say if you try to access testArray[12] . The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.

Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays

In this tutorial, you learned about arrays. These arrays are called one-dimensional arrays.

In the next tutorial, you will learn about multidimensional arrays (array of an array) .

Table of Contents

  • C Arrays (Introduction)
  • Declaring an Array
  • Access array elements
  • Initializing an array
  • Change Value of Array Elements
  • Array Input/Output
  • Example: Calculate Average
  • Array Elements Out of its Bound

Video: C Arrays

Sorry about that.

Related Tutorials

Dey Code

How to Assign Values to an Array of Characters in C – C

Photo of author

The Problem:

When attempting to assign values to an array of characters in C, such as in the provided code, the error message "array type char[30] is not assignable" is encountered. This error occurs because arrays in C are not assignable directly.

The Solution:

Solution 1: using strcpy.

To assign values to a character array in C, you need to use a library function like strcpy. The strcpy function allows you to copy the contents of one string into another. In this case, you can use strcpy(word, "Jump"); to assign the string "Jump" to the character array "word".

Solution 2: Using memcpy

Another option is to use the memcpy function. The memcpy function allows you to copy a specified number of bytes from one memory location to another. In this case, you can use memcpy(word, "Jump", sizeof("Jump")); to assign the string "Jump" to the character array "word".

Conclusion:

In C, arrays of characters cannot be directly assigned values using the assignment operator. Instead, you need to use library functions like strcpy or memcpy to copy the desired string into the character array. By following these solutions, you can successfully assign values to character arrays in C.

  • strcpy – C++ Reference
  • memcpy – Linux Manual

[Fixed] C Error: “Array must be initialized with a brace enclosed initializer” – C

Understanding Format Specifier %02x in C Programming – C

© 2024 deycode.com

char array assignment in c

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

  • Now Trending:
  • How do I check if a list...
  • How do I concatenate two...
  • How to find the index of...
  • How to make a dictionary...

2D character array-String array-Declaration and initialization

In this C Programming tutorial, we will discuss 2D character arrays in detail and will discuss how to declare, initialize and use 2D character arrays or String arrays.

Table of Contents

1. What is 2D character array in C?

We have successfully learned the basic concepts  and different  library functions  that C Programming offers. Another interesting concept is the use of 2D character arrays. In the previous tutorial, we already saw that string is nothing but an array of characters that ends with a ‘\0’ .

2D character arrays are very similar to 2D integer arrays . We store the elements and perform other operations in a similar manner. A 2D character array is more like a String array . It allows us to store multiple strings under the same name.

2. How to Declaration and Initialization a 2D character array?

A 2D character array is declared in the following manner:

The order of the subscripts is important during declaration. The first subscript [5] represents the number of Strings that we want our array to contain and the second subscript [10] represents the length of each String. This is static memory allocation. We are giving 5*10=50 memory locations for the array elements to be stored in the array.

Initialization of the character array occurs in this manner:

Let’s see the diagram below to understand how the elements are stored in the memory location:

The areas marked in green show the memory locations that are reserved for the array but are not used by the string. Each character occupies 1 byte of storage from the memory.

3. How to take 2D array Data input from user?

In order to take string data input from the user we need to follow the following syntax:

Here we see that the second subscript remains [0] . This is because it shows the length of the string and before entering any string the length of the string is 0 .

4. Printing the array elements

The way a 2D character array is printed is not the same as a 2D integer array. This is because we see that all the spaces in the array are not occupied by the string entered by the user.

If we display it in the same way as a 2D integer array we will get unnecessary garbage values in unoccupied spaces. Here is how we can display all the string elements:

This format will print only the string contained in the index numbers specified and eliminate any garbage values after ‘\0’ . All the string library functions that we have come across in the previous tutorials can be used for the operations on strings contained in the string array. Each string can be referred to in this form:

where [i] is the index number of the string that needs to be accessed by library functions.

5. Program to search for a string in the string array

Let’s implement a program to search for a string(a char array) entered by the user in a 2D char array or a string array (also entered by the user):

Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples . All examples are hosted on Github .

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

guest

  • Algorithm Tutorials
  • C Programming Examples
  • C Programming tutorials
  • Complete Python Tutorials – Beginner to Advanced
  • Data Structure Tutorials
  • Python Programming Examples – Basic to Advanced
  • Subscribe to our Newsletter !!
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Convert String to Char Array in C++

  • Convert character array to string in C++
  • Convert char* to string in C++
  • How to Convert a std::string to char* in C++?
  • Convert Vector of chars to String in C++
  • How to convert a single character to string in C++?
  • Array of Pointers to Strings in C++
  • How to Extract a Substring from a Character Array in C++?
  • How to Convert an Integer to a String in C++?
  • Convert given Binary Array to String in C++ with Examples
  • Convert std::string to LPCWSTR in C++
  • C++ - Convert String to Integer Vector
  • How to Compare Two Substrings in a Character Array in C++?
  • How to Resize an Array of Strings in C++?
  • How to Convert a C++ String to Uppercase?
  • C++ Program to Convert String to Integer
  • How to Access Individual Characters in a C++ String?
  • Convert String to Character Array in C#
  • How to Convert a String to a Char Array in C?
  • Different Ways to Convert Char Array to String in C#
  • Vector in C++ STL
  • Initialize a vector in C++ (7 different ways)
  • Map in C++ Standard Template Library (STL)
  • std::sort() in C++ STL
  • Inheritance in C++
  • The C++ Standard Template Library (STL)
  • Object Oriented Programming in C++
  • C++ Classes and Objects
  • Virtual Function in C++
  • Set in C++ Standard Template Library (STL)

Here, we will build a C++ program to convert strings to char arrays. Many of us have encountered the error ‘cannot convert std::string to char[] or char* data type’ so let’s solve this using 5 different methods :

  • Using c_str() with strcpy()
  • Using c_str() without strcpy()
  • Using for loop
  • Using the address assignment of each other method
  • Using data() (C++17 and newer)

1. Using c_str() with strcpy()

A way to do this is to copy the contents of the string to the char array . This can be done with the help of the c_str() and strcpy() functions of library cstring .  The c_str() function is used to return a pointer to an array that contains a null-terminated sequence of characters representing the current value of the string.

If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array. The length of the char array taken should not be less than the length of an input string.

In order to create a new array to contain the characters, we must dynamically allocate the char array with new. We also must remember to use delete[] when we are done with the array. This is done because, unlike C, C++ does not support Variable Length Arrays (VLA) on the stack.

  • Time complexity: O(n)
  • Auxiliary Space: O(1)

2. Using c_str() without strcpy()

An alternate way of Method 1 can be such, without using strcpy() function. This option will not create a new string.

3. Using for loop

We can use for loop to iterate through each element of the std::string and assign the character to the char array one by one.

4. Using the address assignment of each other method

This is the simplest and most efficient one. We can directly assign the address of 1st character of the string to a pointer to the char . This should be the preferred method unless your logic needs a copy of the string.  

5. Using .data() (with C++17 or newer)

Using .data() to access a non-const char* of the std::string is the best option in C++17 or newer. Note: This can’t be run in the GeeksforGeeks IDE because it doesn’t support C++17.

Please Login to comment...

Similar reads.

  • C++ Conversion Programs

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. C++ Char Data Type with Examples (2022)

    char array assignment in c

  2. Convert String to Char Array and Char Array to String in C++

    char array assignment in c

  3. Char array to string C++

    char array assignment in c

  4. Char Array in C

    char array assignment in c

  5. Convert string to char or char array in C#

    char array assignment in c

  6. C

    char array assignment in c

VIDEO

  1. How to declare char, initialize and display char variable in C (Hands-on)

  2. Working with character arrays and "strings" in C

  3. C++ Programming Tutorial

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

  5. Character arrays and pointers

  6. Character Arrays in C Language

COMMENTS

  1. c

    When initializing an array, C allows you to fill it with values. So. char s[100] = "abcd"; is basically the same as. int s[3] = { 1, 2, 3 }; but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

  2. How to Initialize Char Array in C

    Use String Assignment to Initialize a char Array in C. Another useful method to initialize a char array is to assign a string value in the declaration statement. The string literal should have fewer characters than the length of the array; otherwise, there will be only part of the string stored and no terminating null character at the end of the buffer.

  3. Assigning a value to a char array (String) in C

    Because in C arrays are not modifiable lvalues. So you can either initialize the array: char k[25] = "Dennis"; or, use strcpy to copy: strcpy(k, "Dennis"); If you actually have no need for an array, you can simply use a pointer that points to the string literal. The following is valid:

  4. String and Character Arrays in C Language

    String is a sequence of characters that are treated as a single data item and terminated by a null character '\0'.Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in C language. These are often used to create meaningful and readable programs. If you don't know what an array in C means, you can check the C Array ...

  5. C Arrays

    Initialization in C is the process to assign some initial value to the variable. When the array is declared or allocated memory, the elements of the array contain some garbage value. ... Array of Characters (Strings) In C, we store the words, i.e., a sequence of characters in the form of an array of characters terminated by a NULL character ...

  6. Strings in C (With Examples)

    C Programming Strings. In C programming, a string is a sequence of characters terminated with a null character \0. For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default. Memory Diagram.

  7. What is Character Array in C?

    Topics Covered. A Character array is a derived data type in C that is used to store a collection of characters or strings. A char data type takes 1 byte of memory, so a character array has the memory of the number of elements in the array. (1* number_of_elements_in_array). Each character in a character array has an index that shows the position ...

  8. Working with character arrays and "strings" in C

    Learn some basics on character arrays and strings in C. Learn how to declare, modify, output, and manipulate character arrays and C strings.Hope you enjoyed ...

  9. Array of Strings in C

    But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array. Syntax: char variable_name[r] = {list of string}; Here, var_name is the name of the variable in C. r is the maximum number of string values that can be stored in a string array.

  10. Character Array and Character Pointer in C

    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: char arr[] = "Hello World";

  11. C String

    When creating character arrays, leave enough space for the longest string you'll want to store plus account for the string terminator that is included at the end of each string in C. To place or change strings in character arrays you either: Define the array and then assign each individual character element one at a time.

  12. C Arrays (With Examples)

    Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.. Declare an Array Few keynotes:

  13. How to Assign Values to an Array of Characters in C

    Solution 1: Using strcpy. To assign values to a character array in C, you need to use a library function like strcpy. The strcpy function allows you to copy the contents of one string into another. In this case, you can use strcpy (word, "Jump"); to assign the string "Jump" to the character array "word".

  14. Strings in C

    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. char str[] = "GeeksforGeeks"; 2. Assigning a String Literal with a Predefined Size.

  15. Structure Assignment (GNU C Language Manual)

    structure assigment such as r1 = r2 copies array fields' contents just as it copies all the other fields. This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct. You can't copy the contents of the data field as an array, because.

  16. Why does C not support direct array assignment?

    5. In C you cannot assign arrays directly. At first I thought this might because the C facilities were supposed to be implementable with a single or a few instructions and more complicated functionality was offloaded to standard library functions. After all using memcpy() is not that hard.

  17. How to Initialize & Declare 2D character array in C?

    In order to take string data input from the user we need to follow the following syntax: for(i=0 ;i<5 ;i++ ) scanf("%s",&name[i] [0]); Here we see that the second subscript remains [0]. This is because it shows the length of the string and before entering any string the length of the string is 0. 4.

  18. c

    In C, string literals such as "123" are stored as arrays of char (const char in C++). These arrays are stored in memory such that they are available over the lifetime of the program. Attempting to modify the contents of a string literal results in undefined behavior; sometimes it will "work", sometimes it won't, depending on the compiler and ...

  19. c

    It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.. An array char a[SIZE] says that the value at the location of a is an array of length SIZE; A pointer char *a; says that the value at the location of a is a pointer to a char.This can be combined with pointer arithmetic to behave like an array (eg, a[10] is ...

  20. Convert String to Char Array in C++

    string s = "geeksforgeeks"; Output: char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', '\0' }; 1. Using c_str() with strcpy(). A way to do this is to copy the contents of the string to the char array.This can be done with the help of the c_str() and strcpy() functions of library cstring. The c_str() function is used to return a pointer to an array that contains a ...