• 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.

Method Description
It is used to concatenate(combine) two strings
It is used to show the length of a string
It is used to show the reverse of a string
Copies one string into another
It is used to compare two string

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 →

How to assign a string to a char array in C

Answered on: Wednesday 24 January, 2024 / Duration: 12 min read

Programming Language: C , Popularity : 9/10

Solution 1:

Certainly! In C, you can assign a string to a char array using the following methods. Let's go through two common approaches:

### Method 1: Initializing the Char Array Directly

You can initialize a char array directly with a string literal. Here's an example:

### Method 2: Using the strcpy Function

You can also use the strcpy function from the header to copy a string into a char array. Here's an example:

In both methods, the char array is assigned a string, and you can then manipulate or display the content as needed. Note that in Method 2, you need to ensure that the destination char array has enough space to accommodate the string. Adjust the array size accordingly based on the length of your string.

Solution 2:

In C, a string is a sequence of characters, terminated by a null character (\0). A char array is a contiguous block of memory that can store a sequence of characters. To assign a string to a char array, you can use the following steps:

1. Declare a char array with enough space to store the string. 2. Copy the characters of the string to the char array. 3. Append a null character to the end of the char array.

Here is an example of how to assign the string "Hello World" to a char array:

The following is the output of the above code:

Solution 3:

In C, a character array (or "char array") is essentially a sequence of characters that are stored contiguously in memory. A string, on the other hand, is simply a sequence of characters terminated by a null character ('\0'). To assign a string to a char array in C, you can use one of the following methods:

Method 1: Using the strcpy() function from the library

More Articles :

Write a c proogram to find the roots of quadratic equation.

Answered on: Wednesday 24 January, 2024 / Duration: 5-10 min read

Programming Language : C , Popularity : 3/10

time include c

Programming Language : C , Popularity : 9/10

c program to find the factorial of a number

Programming Language : C , Popularity : 8/10

commentaire c

Programming Language : C , Popularity : 10/10

Splash Timer Flutter

Programming Language : C , Popularity : 6/10

how to return two values in c

C style array, c concatenate strings, c programming language.

Programming Language : C , Popularity : 4/10

Counting Sort C

C bit access struct, turn a char into an int in c.

Programming Language : C , Popularity : 5/10

c read file content

How to pass an array of structs as an argument in c.

Programming Language : C , Popularity : 7/10

c how to find size of array

Vim set tab to 4 spaces, markdown c sharp, conda empty environment, parsererror: error tokenizing data. c error: expected 1 fields in line 6, saw 3, clrscr in c, how to change an array in a function in c, making a programming language in c, array value from user c, reattach screen linux, bootsrap textbox, arduino millis, how to run shell command ctrl + c in python script, block a website on mac, floyd's triangle in c.

  • 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

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:

char arr[] = "Hello World"; // array version char ptr* = "Hello World"; // pointer version

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:

character 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.

character 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.

character 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.

gets(arr); scanf("%s", arr); strcpy(arr, "new string"); arr[0] = 'R'; arr[1] = 'e'; arr[2] = 'd'; arr[3] = ' '; arr[4] = 'D'; arr[5] = 'r'; arr[6] = 'a'; arr[7] = 'g'; arr[8] = 'o'; arr[9] = 'n';

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

char *ptr = "Hello"; ptr[0] = 'Y'; or *ptr = 'Y'; gets(name); scanf("%s", ptr); strcpy(ptr, "source"); strcat(ptr, "second string");

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.

ptr[0] = 'H'; gets(ptr); scanf("%s", ptr); strcpy(ptr, "source"); strcat(ptr, "second string");

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

char str[10]; char *p = str;

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

char *ptr; ptr = (char*)malloc(10*sizeof(char)); // allocate memory to store 10 characters

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

#include<stdio.h> #include<stdlib.h> int main() { int n, i; char *ptr; printf("Enter number of characters to store: "); scanf("%d", &n); ptr = (char*)malloc(n*sizeof(char)); for(i=0; i < n; i++) { printf("Enter ptr[%d]: ", i); /* notice the space preceding %c is necessary to read all whitespace in the input buffer */ scanf(" %c", ptr+i); } printf("\nPrinting elements of 1-D array: \n\n"); for(i = 0; i < n; i++) { printf("%c ", ptr[i]); } // signal to operating system program ran fine return 0; }

Expected Output:

Enter number of characters to store: 6 Enter ptr[0]: a Enter ptr[1]: b Enter ptr[2]: c Enter ptr[3]: d Enter ptr[4]: y Enter ptr[5]: z Printing elements of 1-D array: a b c d y z

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

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 Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more.

What is Array in C?

An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived and user-defined data types such as pointers, structures, etc.

arrays in c

C Array Declaration

In C, we have to declare the array like any other variable before using it. We can declare an array by specifying its name, the type of its elements, and the size of its dimensions. When we declare an array in C, the compiler allocates the memory block of the specified size to the array name.

Syntax of Array Declaration

where N is the number of dimensions.

c array delcaration

The C arrays are static in nature, i.e., they are allocated memory at the compile time.

Example of Array Declaration

C array initialization.

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. So, we need to initialize the array to some meaningful value. There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration

In this method, we initialize the array along with its declaration. We use an initializer list to initialize multiple elements of the array. An initializer list is the list of values enclosed within braces { } separated b a comma.

c array initialization

2. Array Initialization with Declaration without Size

If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler can automatically deduce the size of the array in these cases. The size of the array in these cases is equal to the number of elements present in the initializer list as the compiler can automatically deduce the size of the array.

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

We initialize the array after the declaration by assigning the initial value to each element individually. We can use for loop, while loop, or do-while loop to assign the value to each element of the array.

Example of Array Initialization in C

Access array elements.

We can access any element of an array in C using the array subscript operator [ ]  and the index value i of the element.

One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at index 0 and the last element is at N – 1 where N is the number of elements in the array.

access array elements

Example of Accessing  Array Elements using Array Subscript Operator

Update array element.

We can update the value of an element at the given index i in a similar way to accessing an element by using the array subscript operator [ ] and assignment operator = .

C Array Traversal

Traversal is the process in which we visit every element of the data structure. For C array traversal, we use loops to iterate through each element of the array.

Array Traversal using for Loop

c array traversal

How to use Array in C?

The following program demonstrates how to use an array in the C programming language:

Types of Array in C

There are two types of arrays based on the number of dimensions it has. They are as follows:

  • One Dimensional Arrays (1D Array)
  • Multidimensional Arrays

1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one dimension.

Syntax of 1D Array in C

1d array in c

Example of 1D Array in C

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. These are called strings in C language.

To know more about strings, refer to this article – Strings in C

2. Multidimensional Array in C

Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more dimensions than 3d arrays but they are avoided as they get very complex and occupy a large amount of space.

A. Two-Dimensional Array in C

A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be visualized in the form of rows and columns organized in a two-dimensional plane.

Syntax of 2D Array in C

  • size1: Size of the first dimension.
  • size2: Size of the second dimension.

2d array in c

Example of 2D Array in C

B. three-dimensional array in c.

Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on top of each other to create the third dimension.

Syntax of 3D Array in C

3d array in c

Example of 3D Array

To know more about Multidimensional Array in C, refer to this article – Multidimensional Arrays in C

Relationship between Arrays and Pointers

Arrays and Pointers are closely related to each other such that we can use pointers to perform all the possible operations of the array. The array name is a constant pointer to the first element of the array and the array decays to the pointers when passed to the function.

To know more about the relationship between an array and a pointer, refer to this article – Pointer to an Arrays | Array Pointer

Passing an Array to a Function in C

An array is always passed as pointers to a function in C. Whenever we try to pass an array to a function, it decays to the pointer and then passed as a pointer to the first element of an array.

We can verify this using the following C Program:

Return an Array from a Function in C

In C, we can only return a single value from a function. To return multiple values or elements, we have to use pointers. We can return an array from a function using a pointer to the first element of that array.

Note: You may have noticed that we declared static array using static keyword. This is due to the fact that when a function returns a value, all the local variables and other entities declared inside that function are deleted. So, if we create a local array instead of static, we will get segmentation fault while trying to access the array in the main function.

Properties of Arrays in C

It is very important to understand the properties of the C array so that we can avoid bugs while using it. The following are the main properties of an array in C :

1. Fixed Size

The array in C is a fixed-size collection of elements. The size of the array must be known at the compile time and it cannot be changed once it is declared.

2. Homogeneous Collection

We can only store one type of element in an array. There is no restriction on the number of elements but the type of all of these elements must be the same.

3. Indexing in Array

The array index always starts with 0 in C language. It means that the index of the first element of the array will be 0 and the last element will be N – 1.

4. Dimensions of an Array

A dimension of an array is the number of indexes required to refer to an element in the array. It is the number of directions in which you can grow the array size.

5. Contiguous Storage

All the elements in the array are stored continuously one after another in the memory. It is one of the defining properties of the array in C which is also the reason why random access is possible in the array.

6. Random Access

The array in C provides random access to its element i.e we can get to a random element at any index of the array in constant time complexity just by using its index number.

7. No Index Out of Bounds Checking

There is no index out-of-bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run.  

In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just a Warning.

Warnings:  

Examples of Array in C

Example 1: c program to perform array input and output..

In this program, we will use scanf() and print() function to take input and print output for the array.

Example 2: C Program to print the average of the given list of numbers

In this program, we will store the numbers in an array and traverse it to calculate the average of the number stored.

Example 3: C Program to find the largest number in the array.

Advantages of array in c.

The following are the main advantages of an array:

  • Random and fast access of elements using the array index.
  • Use of fewer lines of code as it creates a single array of multiple elements.
  • Traversal through the array becomes easy using a single loop.
  • Sorting becomes easy as it can be accomplished by writing fewer lines of code.

Disadvantages of Array in C

  • Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  • Insertion and deletion of elements can be costly since the elements are needed to be rearranged after insertion and deletion.

The array is one of the most used and important data structures in C. It is one of the core concepts of C language that is used in every other program. Though it is important to know about its limitation so that we can take advantage of its functionality.

C Arrays – FAQs

Define array in c..

An array is a fixed-size homogeneous collection of elements that are stored in a contiguous memory location.

How to declare an array in C?

We can declare array in C using the following syntax: datatype array_name [size];

How do you initialize an array in C?

We can initialize an array using two methods: Using Initializer list Using Loops Using Initializer List We can use an initializer list to initialize the array with the declaration using the following syntax: datatype array_name [size] = {value1, value2,...valueN}; Using Loops We can initialize an Array using Loops in C after the array declaration: for (int i = 0; i < N; i++) { array_name[i] = value i ; }

Why do we need Arrays?

We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.

How can we determine the size of the C array?

We can determine the size of the Array using sizeof Operator in C. We first get the size of the whole array and divide it by the size of each element type.

Please Login to comment...

Similar reads.

  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Best Mobile Game Controllers in 2024: Top Picks for iPhone and Android
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types

C Input Output (I/O)

  • C Programming Operators

C 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

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

Relationship Between Arrays and Pointers

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

C Programming Strings

String Manipulations In C Programming Using Library Functions

  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling

C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Find the Frequency of Characters in a String
  • Sort Elements in Lexicographical Order (Dictionary Order)
  • Remove all Characters in a String Except Alphabets

In C programming, a string is a sequence of characters terminated with a null character \0 . For example:

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 of strings in C programming

  • How to declare a string?

Here's how you can declare strings:

string declaration in C programming

Here, we have declared a string of 5 characters.

  • How to initialize strings?

You can initialize strings in a number of ways.

Initialization of strings in C programming

Let's take another example:

Here, we are trying to assign 6 characters (the last character is '\0' ) to a char array having 5 characters. This is bad and you should never do this.

Assigning Values to Strings

Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example,

Note: Use the strcpy() function to copy the string instead.

Read String from the user

You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Example 1: scanf() to read a string

Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string. It's because there was a space after Dennis .

Also notice that we have used the code name instead of &name with scanf() .

This is because name is a char array, and we know that array names decay to pointers in C.

Thus, the  name  in  scanf() already points to the address of the first element in the string, which is why we don't need to use & .

How to read a line of text?

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()

Here, we have used fgets() function to read a string from the user.

fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the  name string.

To print the string, we have used puts(name); .

Note: The gets() function can also be to take input from the user. However, it is removed from the C standard. It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.

Passing Strings to Functions

Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a function .

Example 3: Passing string to a Function

Strings and pointers.

Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements of the string. We recommended you to check C Arrays and Pointers before you check this example.

Example 4: Strings and Pointers

Commonly used string functions.

  • strlen() - calculates the length of a string
  • strcpy() - copies a string to another
  • strcmp() - compares two strings
  • strcat() - concatenates two strings

Table of Contents

  • Read and Write String: gets() and puts()
  • Passing strings to a function
  • Strings and pointers
  • Commonly used string functions

Video: C Strings

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

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

cppreference.com

Array initialization.

(C11)
Miscellaneous

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 (1)
expression (2) (until C99)
designator(optional) expression (2) (since C99)
(3) (since C23)

Arrays of known size and arrays of unknown size may be initialized , but not VLAs (since C99) (until C23) . A VLA can only be empty-initialized. (since C23)

All array elements that are not initialized explicitly are empty-initialized .

Initialization from strings Initialization from brace-enclosed lists Nested arrays Notes Example References

[ edit ] Initialization from strings

String literal (optionally enclosed in braces) may be used as the initializer for an array of matching type:

  • ordinary string literals and UTF-8 string literals (since C11) can initialize arrays of any character type ( char , signed char , unsigned char )
  • L-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications) wchar_t
(since C11)

Successive bytes of the string literal or wide characters of the wide string literal, including the terminating null byte/character, initialize the elements of the array:

If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:

Note that the contents of such array are modifiable, unlike when accessing a string literal directly with char * str = "abc" ; .

[ edit ] Initialization from brace-enclosed lists

When an array is initialized with a brace-enclosed list of initializers, the first initializer in the list initializes the array element at index zero (unless a designator is specified) (since C99) , and each subsequent initializer without a designator (since C99) initializes the array element at index one greater than the one initialized by the previous initializer.

It's an error to provide more initializers than elements when initializing an array of known size (except when initializing character arrays from string literals).

A designator causes the following initializer to initialize of the array element described by the designator. Initialization then continues forward in order, beginning with the next element after the one described by the designator.

n[5] = {[4]=5,[0]=1,2,3,4}; // holds 1,2,3,4,5   int a[MAX] = { // starts initializing a[0] = 1, a[1] = 3, ... 1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0 }; // for MAX=6, array holds 1,8,6,4,2,0 // for MAX=13, array holds 1,3,5,7,9,0,0,0,8,6,4,2,0 ("sparse array")
(since C99)

When initializing an array of unknown size, the largest subscript for which an initializer is specified determines the size of the array being declared.

[ edit ] Nested arrays

If the elements of an array are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:

If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding array element:

If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the sub-array, struct or union; any remaining initializers are left to initialize the next array element:

Array designators may be nested; the bracketed constant expression for nested arrays follows the bracketed constant expression for the outer array:

y[4][3] = {[0][0]=1, [1][1]=1, [2][0]=1}; // row 0 initialized to {1, 0, 0} // row 1 initialized to {0, 1, 0} // row 2 initialized to {1, 0, 0} // row 3 initialized to {0, 0, 0}
(since C99)

[ edit ] Notes

The order of evaluation of subexpressions in an array initializer is indeterminately sequenced in C (but not in C++ since C++11):

In C, the braced list of an initializer cannot be empty. C++ allows empty list:

(until C23)

An empty initializer can be used to initialize an array:

(since C23)

As with all other initialization , every expression in the initializer list must be a constant expression when initializing arrays of static or thread-local storage duration :

[ edit ] Example

[ edit ] references.

  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.9/12-39 Initialization (p: 101-105)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.9/12-38 Initialization (p: 140-144)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.8/12-38 Initialization (p: 126-130)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 6.5.7 Initialization
  • 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 16 October 2022, at 11:04.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

C Functions

C structures, c reference.

Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must use the char type and create an array of characters to make a string in C:

Note that you have to use double quotes ( "" ).

To output the string, you can use the printf() function together with the format specifier %s to tell C that we are now working with strings:

Access Strings

Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [] .

This example prints the first character (0) in greetings :

Note that we have to use the %c format specifier to print a single character .

Modify Strings

To change the value of a specific character in a string, refer to the index number, and use single quotes :

Loop Through a String

You can also loop through the characters of a string, using a for loop:

And like we specified in the arrays chapter, you can also use the sizeof formula (instead of manually write the size of the array in the loop condition (i < 5) ) to make the loop more sustainable:

Another Way Of Creating Strings

In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a string in C.

You should also note that you can create a string with a set of characters. This example will produce the same result as the example in the beginning of this page:

Why do we include the \0 character at the end? This is known as the "null terminating character", and must be included when creating strings using this method. It tells C that this is the end of the string.

Differences

The difference between the two ways of creating strings, is that the first method is easier to write, and you do not have to include the \0 character, as C will do it for you.

You should note that the size of both arrays is the same: They both have 13 characters (space also counts as a character by the way), including the \0 character:

Real-Life Example

Use strings to create a simple welcome message:

C Exercises

Test yourself with exercises.

Fill in the missing part to create a "string" named greetings , and assign it the value "Hello".

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

character array assignment in c




Tutorials








Practice




Resources







References




This tip submitted by Brian Plummer on 2010-12-26 17:05:00. It has been viewed 25991 times.
Rating of 4.3 with 69 votes



When a is defined it can be initialised with a string constant, creating a :



To copy String1 char array to String2 char array, you cannot simply assign the whole array to it, it has to be copied one character at a time within a loop, or use a string copy function in the standard library. However, when string arrays are within a they can be simply assigned:


Now String2.String array is equal to String1.String array.

Of course, if you're working in C++, it's much easier to simply use which to make this simple.





| | | |

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Character Pointers and Functions in C

What is a character pointer in c.

A character pointer stores the address of a character type or address of the first character of a character array ( string ). Character pointers are very useful when you are working to manipulate the strings.

There is no string data type in C. An array of "char" type is considered as a string. Hence, a pointer of a char type array represents a string. This char pointer can then be passed as an argument to a function for processing the string.

Declaring a Character Pointer

A character pointer points to a character or a character array. Thus, to declare a character pointer, use the following syntax:

Initializing a Character Pointer

After declaring a character pointer, you need to initialize it with the address of a character variable. If there is a character array, you can simply initialize the character pointer by providing the name of the character array or the address of the first elements of it.

Character Pointer of Character

The following is the syntax to initialize a character pointer of a character type:

Character Pointer of Character Array

The following is the syntax to initialize a character pointer of a character array (string):

Character Pointer Example

In the following example, we have two variables character and character array. We are taking two pointer variables to store the addresses of the character and character array, and then printing the values of the variables using the character pointers.

Run the code and check its output −

The library functions in the header file "string.h" processes the string with char pointer parameters.

Understanding Character Pointer

A string is declared as an array as follows −

The string is a NULL terminated array of characters. The last element in the above array is a NULL character (\0).

Declare a pointer of char type and assign it the address of the character at the 0th position −

Remember that the name of the array itself is the address of 0th element.

A string may be declared using a pointer instead of an array variable (no square brackets).

This causes the string to be stored in the memory, and its address stored in ptr . We can traverse the string by incrementing the ptr .

Accessing Character Array

If you print a character array using the %s format specifier, you can do it by using the name of the character pointer. But if you want to access each character of the character array, you have to use an asterisk ( * ) before the character pointer name and then increment it.

Here is the full program code −

Alternatively, pass ptr to printf() with %s format to print the string.

On running this code, you will get the same output −

Character Pointer Functions

The "string.h" header files defines a number of library functions that perform string processing such as finding the length of a string, copying a string and comparing two strings. These functions use char pointer arguments.

The strlen() Function

The strlen() function returns the length, i.e. the number of characters in a string. The prototype of strlen() function is as follows −

The following code shows how you can print the length of a string −

When you run this code, it will produce the following output −

Effectively, the strlen() function computes the string length as per the user-defined function str_len() as shown below −

The strcpy() Function

The assignment operator ( = ) is not used to assign a string value to a string variable, i.e., a char pointer. Instead, we need to use the strcpy() function with the following prototype −

The following example shows how you can use the strcpy() function −

The strcpy() function returns the pointer to the destination string ptr1 .

Internally, the strcpy() function implements the following logic in the user-defined str_cpy() function −

When you runt his code, it will produce the following output −

The function copies each character from the source string to the destination till the NULL character "\0" is reached. After the loop, it adds a "\0" character at the end of the destination array.

The strcmp() Function

The usual comparison operators (<, >, <=, >=, ==, and !=) are not allowed to be used for comparing two strings. Instead, we need to use strcmp() function from the "string.h" header file. The prototype of this function is as follows −

The strcmp() function has three possible return values −

  • When both strings are found to be identical , it returns "0".
  • When the first not-matching character in str1 has a greater ASCII value than the corresponding character in str2, the function returns a positive integer . It implies that str1 appears after str2 in alphabetical order, as in a dictionary.
  • When the first not-matching character in str1 has a lesser ASCII value than the corresponding character in str2, the function returns a negative integer . It implies that str1 appears before str2 in alphabetical order, as in a dictionary.

The following example demonstrates how you can use the strcmp() function in a C program −

Change s1 to BACK and run the code again. Now, you will get the following output −

You can obtain a similar result using the user-defined function str_cmp() , as shown in the following code −

The str_cmp() function compares the characters at the same index in a string till the characters in either string are exhausted or the characters are equal.

At the time of detecting unequal characters at the same index, the difference in their ASCII values is returned. It returns "0" when the loop is terminated.

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • assign to char * array

  assign to char * array

character array assignment in c

* a = ; a[0]= ; cout<<a[0];
* a = ;
a[] = ; a[0] = ;
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assigning a character array to a character array in a structure

I am working on a project that requires that I make an array of a certain structure type. The structure looks like this:

I have declared an array of these structures like this:

I passed this structure array to a function which fills the first four elements with a string and a number. The fifth is left blank. Later in the program, I pass the array again and try to set the string in the structure to a user determined string using gets(). I am getting this error:

If I need to provide more clarification, please tell me.

EDIT: Here is what I am doing:

user3014065's user avatar

  • 3 Please add the code where you're passing the array of structures to the function. –  Fiddling Bits Commented Nov 20, 2013 at 17:23
  • use strcpy and not operator = –  Florian Groetzner Commented Nov 20, 2013 at 17:25
  • Never ever use gets() . It is dangerous, it is deprecated, it is removed from C++ and should be removed from C too. –  n. m. could be an AI Commented Nov 20, 2013 at 17:33

2 Answers 2

you are doing something like this

you cant do this.

do strcpy(a,"bla"); instead. ( #include <string.h> )

Florian Groetzner's user avatar

Without looking at the code you are probably trying to do something like:

which won't work, as you can't assign the returned char* from gets to an array as the compiler says. You are also using gets , which is strongly discouraged as it performs no bounds checking. Instead, do the following:

which will do proper bounds checking.

John Källén's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c arrays structure or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Best approach to make lasagna fill pan
  • Could a lawyer agree not to take any further cases against a company?
  • Why isn't a confidence level of anything >50% "good enough"?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • What is the optimal number of function evaluations?
  • Which volcano is more hazardous? Mount Rainier or Mount Hood?
  • How do I prove the amount of a flight delay in UK court?
  • How cheap would rocket fuel have to be to make Mars colonization feasible (according to Musk)?
  • Book about a wormhole found inside the Moon
  • Topos notions coming from topology and uniqueness of generalizations
  • Beatles reference in parody story from the 1980s
  • What are the steps to write a book?
  • How would you read this time change with the given note equivalence?
  • Swapping touch digitizer from one Android phone to another
  • How to truncate text in latex?
  • What would be a good weapon to use with size changing spell
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • What's the best format or way to generate a short-lived access token?
  • Filtering polygons by name in one column of QGIS Attribute Table
  • Colossians 1:16 New World Translation renders τα πάντα as “all other things” but why is this is not shown in their Kingdom Interlinear?
  • Is this host and 'parasite' interaction feasible?
  • Setting the desired kernel in GRUB menu
  • How high does the ocean tide rise every 90 minutes due to the gravitational pull of the space station?
  • How is causality in Laplace transform related to Fourier transform?

character array assignment in c

IMAGES

  1. How to Program in C++ Episode 6 [Character Arrays]

    character array assignment in c

  2. Character Arrays in C++

    character array assignment in c

  3. Add Space To Char Array C++

    character array assignment in c

  4. C# Arrray: An Introductory Guide for Getting Started

    character array assignment in c

  5. Ways to take character array as an input in C++

    character array assignment in c

  6. Strings in C and Char Arrays Tutorial and Important Interview MCQ

    character array assignment in c

VIDEO

  1. String in c

  2. Lecture 17: String in C++

  3. SGD Array Assignment

  4. Programming C# for Beginners Episode-3: Operators

  5. # 21 Strings(Character array) in C Programming

  6. Arrays in C Language || Array Types || Sum of all digits using array || C Tutorial || #ctutorial

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. Array of Strings in C

    Learn how to declare and use an array of strings in C, a two-dimensional array of character types. See syntax, examples and output of printing string array elements.

  3. String and Character Arrays in C Language

    Learn how to declare, initialize, input and output strings in C language using character arrays. Also, explore the common string handling functions such as strcat, strlen, strrev, strcpy and strcmp.

  4. How to assign a string to a char array in C

    A char array is a contiguous block of memory that can store a sequence of characters. To assign a string to a char array, you can use the following steps: 1. Declare a char array with enough space to store the string. 2. Copy the characters of the string to the char array. 3. Append a null character to the end of the char array. Here is an ...

  5. 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.

  6. Strings in C

    Learn how to declare, initialize, read, and print strings in C programming. A string is a sequence of characters terminated with a null character '\\0' and stored as an array of characters.

  7. Character Array and Character Pointer in C

    Learn the difference between character array and character pointer in C programming, with examples and explanations. See how to declare, initialize, assign, and manipulate strings using arrays and pointers.

  8. C Arrays (With Examples)

    Learn how to declare, initialize and access array elements in C. An array is a variable that can store multiple values of the same type. See examples of one-dimensional and multidimensional arrays.

  9. What is Character Array in C?

    Learn what a character array is, how to create and initialize it, and how to use it for various operations in C. See examples of converting integers, arrays, strings, and durations to character arrays.

  10. c++

    The char array a will be static and can not be changed if you initialize it like this. Anyway you can never assign a character string a="iqbal" in c. You have to use strncpy or memcpy for that. Otherwise you will try to overwrite the pointer to the string, and that is not what you want. So the correct code would do something like:

  11. C Arrays

    Learn how to declare, initialize, access, update, and traverse arrays in C language. Explore the types, advantages, and disadvantages of arrays, and examples of 1D, 2D, and 3D arrays.

  12. Strings in C (With Examples)

    Learn how to declare, initialize and manipulate strings in C programming with examples and functions. See how to read, write and pass strings to functions using scanf(), fgets(), puts() and pointers.

  13. C String

    Learn how to use char data type, variables, arrays and string terminators to declare strings in C. See examples of how to initialize, assign and access strings in C code.

  14. Array initialization

    Learn how to initialize arrays in C with string literals, brace-enclosed lists, or empty initializers. See examples, syntax, and rules for arrays of known or unknown size, nested arrays, and VLAs.

  15. C Strings

    Learn how to create, access, modify and loop through strings in C, a popular programming language. Strings are arrays of characters that store text or characters, and can be created with string literals or character arrays.

  16. Assigning a char array to another char array

    To copy String1 char array to String2 char array, you cannot simply assign the whole array to it, it has to be copied one character at a time within a loop, or use a string copy function in the standard library. However, when string arrays are within a structure they can be simply assigned: struct StringStruct. {. unsigned char String[20];

  17. Character Pointers and Functions in C

    Learn how to declare, initialize and use character pointers to manipulate strings in C. See examples of strlen(), strcpy() and other string functions that use char pointers.

  18. C array declaration and assignment?

    You see, in C the name of an array is a pointer that points to the start of the array. In fact, arrays and pointers are essentially interchangable. You can take any pointer and index it like an array. Back when C was being developed in the early 70's, it was meant for relatively small programs that were barely above assembly language in ...

  19. assign to char * array

    It is a nameless, read-only char array. So the correct definition of a would actually be: 1. 2. const char * a = "some text"; // read as: `a` is a pointer to const char. You can take the memory address of the string literal "some text", but you may not change its contents. With that out of the way, you probably wanted to define a char array.

  20. c

    Without looking at the code you are probably trying to do something like: struct[4].array = gets(<unknown>); which won't work, as you can't assign the returned char* from gets to an array as the compiler says. You are also using gets, which is strongly discouraged as it performs no bounds checking. Instead, do the following: