Home » Learn C Programming from Scratch » C Character Type

C Character Type

Summary : in this tutorial, you will learn what C character type is and how to declare, use and print character variables in C.

C uses char type to store characters and letters. However, the char type is  integer type because underneath C stores integer numbers instead of characters.

To represent characters, the computer has to map each integer with a corresponding character using a numerical code. The most common numerical code is ASCII, which stands for American Standard Code for Information Interchange.

The following table illustrates the ASCII code:

For example, the integer number 65 represents a character A  in upper case.

In C, the char type has a 1-byte unit of memory so it is more than enough to hold the ASCII codes. Besides ASCII code, there are various numerical codes available such as extended ASCII codes. Unfortunately, many character sets have more than 127 even 255 values. Therefore, to fulfill those needs, Unicode was created to represent various available character sets. Unicode currently has over 40,000 characters.

Using C char  type

In order to declare a  variable with character type, you use the  char keyword followed by the variable name. The following example declares three char variables.

In this example, we initialize a character variable with a character literal. A character literal contains one character that is surrounded by a single quotation ( ' ).

The following example declares  key character variable and initializes it with a character literal ‘ A ‘:

Because the char type is the integer type, you can initialize or assign a char variable an integer. However, it is not recommended since the code may not be portable.

Displaying C character type

To print characters in C, you use the  printf()   function with %c  as a placeholder. If you use %d , you will get an integer instead of a character. The following example demonstrates how to print characters in C.

In this tutorial, you have learned about C character type and how to declare, use and print character variables 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:

c character assignment

On the other hand when the compiler sees the statement.

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

c character assignment

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

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

c character assignment

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
  • 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++ Tutorial
  • Java Tutorial
  • Python Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • C Introduction
  • C Data Types and Modifiers
  • C Naming Conventions
  • C Integer Variable
  • C Float and Double Variables
  • C Character Variable
  • C Constant Variable
  • C Typecasting
  • C Operators
  • C Assignment Operators
  • C Arithmetic Operators
  • C Relational Operators
  • C Logical Operators
  • C Operator Precedence
  • C Environment Setup
  • C Program Basic Structure
  • C printf() Function
  • C scanf() Function
  • C Decision Making
  • C if Statement
  • C if else Statement
  • C if else if Statement
  • C Conditional Operator
  • C switch case Statement
  • C Mathematical Functions
  • C while Loop
  • C do while Loop
  • C break and continue
  • C One Dimensional Array
  • C Two Dimensional Array
  • C String Methods
  • C Bubble Sort
  • C Selection Sort
  • C Insertion Sort
  • C Linear Search
  • C Binary Search
  • C Dynamic Memory Allocation
  • C Structure
  • C Recursive Function
  • C Circular Queue
  • C Double Ended Queue
  • C Singly Linked List
  • C Doubly Linked List
  • C Stack using Linked List
  • C Queue using Linked List
  • C Text File Handling
  • C Binary File Handling

How to Declare and Use Character Variables in C Programming

C basic concepts.

In this lesson, we will discover how to declare and use character variables in C programming with this practical guide. Get hands-on with examples and take a quiz to reinforce your understanding.

What is Character Variable

In C programming, a character variable can hold a single character enclosed within single quotes. To declare a variable of this type, we use the keyword char , which is pronounced as kar . With a char variable, we can store any character, including letters, numbers, and symbols.

video-poster

Syntax of Declaring Character Variable in C

Here char is used for declaring Character data type and variable_name is the name of variable (you can use any name of your choice for example: a, b, c, alpha, etc.) and ; is used for line terminator (end of line).

Now let's see some examples for more understanding.

Declare a character variable x .

Declare 3 character variables x , y , and z to assign 3 different characters in it.

Note: A character can be anything, it can be an alphabet or digit or any other symbol, but it must be single in quantity.

Declare a character variable x and assign the character '$' and change it value to @ in the next line.

Test Your Knowledge

Attempt the multiple choice quiz to check if the lesson is adequately clear to you.

Test Your Knowledge

For over a decade, Dremendo has been recognized for providing quality education. We proudly introduce our newly open online learning platform, which offers free access to popular computer courses.

Our Courses

News updates.

  • Refund and Cancellation
  • Privacy Policy

Popular Articles

  • C Language Library (Feb 06, 2024)
  • C Programming Language Examples (Nov 30, 2023)
  • C Programming Fgets (Nov 30, 2023)
  • C Programming Enum (Nov 30, 2023)
  • C Programming Char (Nov 30, 2023)

C Programming Char

Switch to English

Table of Contents

Introduction

Understanding the char data type, declaring and initializing char variables, printing char variables, common pitfalls and how to avoid them.

  • One of the most fundamental data types in C programming is the Char data type. It's used to store characters, which can be letters, numbers, or any other symbols that can be represented in ASCII format. Understanding how to work with Char in C is crucial for everyone learning this programming language, as it forms the basis for handling text and strings.
  • The Char data type, which stands for 'character', is used to store a single character. This could be a letter, a number, a punctuation mark, a space, or any other symbol that can be represented in ASCII format. Each character occupies one byte of memory, which means it can represent 256 different values (from 0 to 255). Most commonly, these values are interpreted as the ASCII values of characters.
  • For example, the ASCII value of 'A' is 65, while the ASCII value of 'a' is 97. Thus, in C, you can initialize a Char variable to hold either a character or its corresponding ASCII value:
  • To declare a Char variable in C, you simply use the char keyword, followed by the name of the variable. You can optionally initialize it at the same time. For example:
  • Once a Char variable has been declared, you can assign it a value using the assignment operator (=). For example, the following code assigns the character 'C' to the previously declared variable myChar:
  • To print a Char variable, you can use the printf function with the %c format specifier. For example, the following code prints the value of the myChar variable:
  • One common mistake when working with Char variables in C is forgetting that they can store not just letters, but any ASCII character. This includes non-printable characters, which can lead to unexpected results when printed. To avoid this, always ensure that your Char variables are initialized with printable characters or their corresponding ASCII values.
  • Another common error is expecting Char variables to behave like String variables. In C, a string is simply an array of Char variables, terminated by the null character ('\0'). Thus, while you can assign a single character to a Char variable, you cannot assign a string of characters without first declaring it as an array:
  • Finally, remember that Char variables are case-sensitive. This means that 'A' and 'a' are considered different characters, with different ASCII values. Always take this into account when comparing Char variables or assigning them values.
  • Working with Char variables in C is a fundamental skill for any programmer. By understanding how they store data and how to manipulate this data, you can create more complex and powerful programs. As with any aspect of programming, practice is key – so keep experimenting with different ways to use Char variables in your programs.

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

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.

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

Strings in C

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

string in c

C String Declaration Syntax

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

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

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

C String Initialization

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

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

1. Assigning a String Literal without Size

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

2. Assigning a String Literal with a Predefined Size

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

3. Assigning Character by Character with Size

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

4. Assigning Character by Character without Size

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

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

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

C String Example

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

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

Read a String Input From the User

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

       

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

Now consider one more example,

 

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

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

How to Read a String Separated by Whitespaces in C?

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

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

1. Example of String Input using gets()

2. Example of String Input using scanset

C String Length

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

Passing Strings to Function

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

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

Strings and Pointers in C

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

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

memory representation of strings

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

 

Standard C Library – String.h  Functions

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

Function Name Description
Returns the length of string name.
Copies the contents of string s2 to string s1.
Compares the first string with the second string. If strings are the same it returns 0.
Concat s1 string with s2 string and the result is stored in the first string.
Converts string to lowercase.
Converts string to uppercase.
Find the first occurrence of s2 in s1.
  • puts() vs printf() to print a string
  • Swap strings in C
  • Storage for strings in C
  • gets() is risky to use!

Please Login to comment...

Similar reads.

  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Search anything:

Working with character (char) in C

Software engineering c programming.

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 30 minutes

C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255. In order to represent characters, the computer has to map each integer with a corresponding character using a numerical code. The most common numerical code is ASCII, which stands for American Standard Code for Information Interchange.

How to declare characters?

To declare a character in C, the syntax:

Complete Example in C:

C library functions for characters

The Standard C library #include <ctype.h> has functions you can use for manipulating and testing character values:

How to convert character to lower case?

  • int islower(ch)

Returns value different from zero (i.e., true) if indeed c is a lowercase alphabetic letter. Zero (i.e., false) otherwise.

How to convert character to upper case?

  • int isupper(ch)

A value different from zero (i.e., true) if indeed c is an uppercase alphabetic letter. Zero (i.e., false) otherwise.

Check if character is an alphabet?

  • isalpha(ch)

Returns value different from zero (i.e., true) if indeed c is an alphabetic letter. Zero (i.e., false) otherwise.

Check if character is a digit

  • int isdigit(ch);

Returns value different from zero (i.e., true) if indeed c is a decimal digit. Zero (i.e., false) otherwise.

Check if character is a digit or alphabet

  • int isalnum(ch);

Returns value different from zero (i.e., true) if indeed c is either a digit or a letter. Zero (i.e., false) otherwise.

Check if character is a punctuation

  • int ispunct(ch)

Returns value different from zero (i.e., true) if indeed c is a punctuation character. Zero (i.e., false) otherwise.

Check if character is a space

  • int isspace(ch)

Retuns value different from zero (i.e., true) if indeed c is a white-space character. Zero (i.e., false) otherwise.

  • char tolower(ch) & char toupper(ch)

The value of the character is checked other if the vlaue is lower or upper case otherwise it is change and value is returned as an int value that can be implicitly casted to char.

Find size of character using Sizeof()?

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes.

In the below example the size of char is 1 byte, but the type of a character constant like 'a' is actually an int, with size of 4.

  • All the function in Ctype work under constant time

What are the different characters supported?

The characters supported by a computing system depends on the encoding supported by the system. Different encoding supports different character ranges.

Different encoding are:

ASCII encoding has most characters in English while UTF has characters from different languages.

char_ASCII-1

Consider the following C++ code:

What will be the output of the above code?

OpenGenus IQ: Learn Algorithms, DL, System Design icon

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

  assign to char * array

c character assignment

* a = ; a[0]= ; cout<<a[0];
* a = ;
a[] = ; a[0] = ;

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

Operator Operator name Example Description Equivalent of
= basic assignment a = b becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b

a[b]
*a
&a
a->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

for Assignment operators
  • 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 19 August 2022, at 09:36.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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.

C Language Tutorial

c character assignment

C Operators

C control structure, branch & jump stmt, character set in c programming language.

The C character set, also known as the ASCII character set, is a set of characters that can be used in the C programming language. The term "ASCII" stands for American Standard Code for Information Interchange. Originally developed in the 1960s, ASCII is a widely used character encoding standard that defines numeric codes for various characters.

In the C character set, the basic set of characters consists of 128 characters, including:

Table of content For Character Set
The uppercase lettersA to Z (65 to 90)
The lowercase lettersa to z (97 to 122)
The decimal digits 0 to 9 (48 to 57)
Special characters punctuation marks, spaces, and mathematical symbols
Control charactersnewline, carriage return, and tab

The ASCII character set is a subset of the Unicode character set, which is a more comprehensive character encoding standard that supports characters from various languages and scripts worldwide. However, for compatibility and historical reasons, the C programming language still primarily relies on the ASCII character set.

In addition to the basic ASCII characters, the C language also defines escape sequences that represent special characters using backslash () followed by a specific character. For example, '\n' represents a newline character, '\t' represents a tab character, and '\' represents a backslash character.

It's worth noting that the C character set has been extended to include additional characters beyond the original ASCII set. This extension is known as the "extended character set" and includes characters with numeric codes greater than 127. The exact set of extended characters may vary depending on the implementation and locale settings of the C programming environment.

  • Learn C Language
  • Learn C++ Language
  • Learn python Lang

Learn C++ practically and Get Certified .

Popular Tutorials

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

  • Getting Started With C++
  • Your First C++ Program
  • C++ Comments

C++ Fundamentals

  • C++ Keywords and Identifiers
  • C++ Variables, Literals and Constants

C++ Data Types

  • C++ Type Modifiers
  • C++ Constants

C++ Basic Input/Output

  • C++ Operators

Flow Control

  • C++ Relational and Logical Operators
  • C++ if, if...else and Nested if...else
  • C++ for Loop
  • C++ while and do...while Loop
  • C++ break Statement
  • C++ continue Statement
  • C++ goto Statement
  • C++ switch..case Statement
  • C++ Ternary Operator
  • C++ Functions
  • C++ Programming Default Arguments
  • C++ Function Overloading
  • C++ Inline Functions
  • C++ Recursion

Arrays and Strings

  • C++ Array to Function
  • C++ Multidimensional Arrays
  • C++ String Class

Pointers and References

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ References: Using Pointers
  • C++ Call by Reference: Using pointers
  • C++ Memory Management: new and delete

Structures and Enumerations

  • C++ Structures
  • C++ Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

Object Oriented Programming

  • C++ Classes and Objects
  • C++ Constructors
  • C++ Constructor Overloading
  • C++ Destructors
  • C++ Access Modifiers
  • C++ Encapsulation
  • C++ friend Function and friend Classes

Inheritance & Polymorphism

  • C++ Inheritance
  • C++ Public, Protected and Private Inheritance
  • C++ Multiple, Multilevel and Hierarchical Inheritance
  • C++ Function Overriding
  • C++ Virtual Functions
  • C++ Abstract Class and Pure Virtual Function

STL - Vector, Queue & Stack

  • C++ Standard Template Library
  • C++ STL Containers
  • C++ std::array
  • C++ Vectors
  • C++ Forward List
  • C++ Priority Queue

STL - Map & Set

  • C++ Multimap
  • C++ Multiset
  • C++ Unordered Map
  • C++ Unordered Set
  • C++ Unordered Multiset
  • C++ Unordered Multimap

STL - Iterators & Algorithms

  • C++ Iterators
  • C++ Algorithm
  • C++ Functor

Additional Topics

  • C++ Exceptions Handling
  • C++ File Handling
  • C++ Ranged for Loop
  • C++ Nested Loop
  • C++ Function Template
  • C++ Class Templates
  • C++ Type Conversion
  • C++ Type Conversion Operators
  • C++ Operator Overloading

Advanced Topics

  • C++ Namespaces
  • C++ Preprocessors and Macros
  • C++ Storage Class
  • C++ Bitwise Operators
  • C++ Buffers

C++ istream

  • C++ ostream

C++ Tutorials

  • Find ASCII Value of a Character
  • C++ tolower()
  • C++ toupper()
  • C++ ispunct()
  • C++ isspace()

In C++, the char keyword is used to declare character type variables. A character variable can store only a single character.

Example 1: Printing a char variable

In the example above, we have declared a character type variable named ch . We then assigned the character h to it.

Note: In C and C++, a character should be inside single quotation marks. If we use, double quotation marks, it's a string.

  • ASCII Value

In C and C++, an integer (ASCII value) is stored in char variables rather than the character itself. For example, if we assign 'h' to a char variable, 104 is stored in the variable rather than the character itself. It's because the ASCII value of 'h' is 104.

Here is a table showing the ASCII values of characters A , Z , a , z and 5 .

Characters ASCII Values
65
90
97
122
53

To learn more about ASCII code , visit the ASCII Chart .

Example 2: Get ASCII Value of a Character

We can get the corresponding ASCII value of a character by using int() when we print it.

We can assign an ASCII value (from 0 to 127 ) to the char variable rather than the character itself.

Example 3: Print Character Using ASCII Value

Note: If we assign '5' (quotation marks) to a char variable, we are storing 53 (its ASCII value). However, if we assign 5 (without quotation marks) to a char variable, we are storing the ASCII value 5 .

  • C++ Escape Sequences

Some characters have special meaning in C++, such as single quote ' , double quote " , backslash \ and so on. We cannot use these characters directly in our program. For example,

Here, we are trying to store a single quote character ' in a variable. But this code shows a compilation error.

So how can we use those special characters?

To solve this issue, C++ provides special codes known as escape sequences. Now with the help of escape sequences, we can write those special characters as they are. For example,

Here, \' is an escape sequence that allows us to store a single quote in the variable.

The table below lists escape sequences of C++.

Escape Sequences Characters
Backspace
Form feed
Newline
Return
Horizontal tab
Vertical tab
Backslash
Single quotation mark
Double quotation mark
Question mark
Null Character

Example 4: Using C++ Escape Sequences

In the above program, we have used two escape sequences: the horizontal tab \t and the new line \n .

Table of Contents

  • Introduction

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++ Tutorial

C++ Strings

  • 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 value to char array [duplicate]

I get no error when I type

But when I change it to the following, I get an error: Array type char is not assignable.

Why is array type char not assignable? Is it because the language is written that way on purpose or am I missing a point?

Rutvij Kotecha's user avatar

  • For responses: Since this is tagged C++, is there a non -strcpy "more C++" way to do this while dealing with char[] ? –  user166390 Commented Feb 16, 2013 at 22:56
  • A "more C++ way" would be to use string or vector<char> instead of char[]. By using char[] you're basically accepting all the C-ness that goes with it. –  Cogwheel Commented Feb 16, 2013 at 23:07
  • Nominated to reopen because this is tagged c++ and the "duplicate" says "in C". I know the answer is the same either way, but they're still different languages and the answer is subject to change or have subtleties worth pointing out here. –  Jim Hunziker Commented Feb 16, 2018 at 15:31

7 Answers 7

An array is not a modifiable lvalue

learnvst's user avatar

The C++ way of doing this, as I commented above, would be to use std::string instead of char[] . That will give you the assignment behavior you're expecting.

That said, the reason you're only getting an error for the second case is that the = in these two lines mean different things:

The first is an initialization, the second is an assignment.

The first line allocates enough space on the stack to hold 10 characters, and initializes the first three of those characters to be 'H', 'i', and '\0'. From this point on, all a does is refer to the position of the the array on the stack. Because the array is just a place on the stack, a is never allowed to change. If you want a different location on the stack to hold a different value, you need a different variable.

The second (invalid) line, on the other hand, tries to change a to refer to a (technically different) incantation of "Hi" . That's not allowed for the reasons stated above. Once you have an initialized array, the only thing you can do with it is read values from it and write values to it. You can't change its location or size. That's what an assignment would try to do in this case.

Cogwheel's user avatar

  • 1 Would you mind including that you could use a std::string and get the behavior the OP wants? I think that would be a good addition to a good answer. –  NathanOliver Commented Mar 11, 2016 at 16:25
  • 1 Yeah, I usually try to give two tier answers to questions like this (one direct, the other second-guessing the intent). Since the asker had seen my comment and this thread got closed as dupe, I guess I didn't bother. –  Cogwheel Commented Mar 11, 2016 at 17:29

The language does not allow assigning string literals to character arrays. You should use strcpy() instead:

NPE's user avatar

  • 1 Correct -- for a situation like this you should use strcpy . Forgetting you ever even heard of strncpy would probably be no loss at all -- it's almost as useless as gets . –  Jerry Coffin Commented Feb 17, 2013 at 0:37
  • Related Difference between 'strcpy' and 'strcpy_s'? –  Quazi Irfan Commented Mar 3, 2017 at 5:45

a is a pointer to the array, not the array itself. It cannot be reassigned.

You tagged with C++ BTW. For that case better use std::string. It's probably more what you're expecting.

  • 1 a is the array itself, not a pointer to the array. It can be implicitly converted to a pointer to the first element. –  Joseph Mansfield Commented Feb 16, 2013 at 22:48

Simple, the

is a little "extra feature", as it cannot be done like that on run-time.

But that's the reason for C/C++ standard libraries.

This comes from the C's standard library. If using C++ you should use std::string, unless you really want to suck all the possible performance from your destination PC.

SGH's user avatar

this is because initialization is not an assignment. the first thing which works is an initialization, and the second one, which does not work, as expected, is assignment. you simply cant assign values to arrays you should use sth like strcpy or memcpy . or you can alternatively use std::copy from <algorithm>

Hayri Uğur Koltuk's user avatar

It is so simple,(=) have two different mean assignment and initialization. You can also write your code like that

in this code you have no need to write a difficult code or function and even no need of string.h

Muhammad Shujauddin's user avatar

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

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • 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

  • What is the difference between using a resistor or a capacitor as current limiter?
  • What happens when a helicopter loses the engine and autorotation is not initiated?
  • Philosophies about how childhood beliefs influence / shape adult thoughts
  • What explanations can be offered for the extreme see-sawing in Montana's senate race polling?
  • Flyback Controller IC identification
  • Reusing own code at work without losing licence
  • Do metal objects attract lightning?
  • wp_verify_nonce is always false even when the nonces are identical
  • Stuck on Sokoban
  • Fill a grid with numbers so that each row/column calculation yields the same number
  • `Drop` for list of elements of different dimensions
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • My school wants me to download an SSL certificate to connect to WiFi. Can I just avoid doing anything private while on the WiFi?
  • about flag changes in 16-bit calculations on the MC6800
  • Simple casino game
  • Using "no" at the end of a statement instead of "isn't it"?
  • Can I use "historically" to mean "for a long time" in "Historically, the Japanese were almost vegetarian"?
  • What is an intuitive way to rename a column in a Dataset?
  • I'm trying to remember a novel about an asteroid threatening to destroy the earth. I remember seeing the phrase "SHIVA IS COMING" on the cover
  • Is it possible to create a board position where White must make the move that leads to stalemating Black to avoid Black stalemating White?
  • Can a rope thrower act as a propulsion method for land based craft?
  • I don’t know what to buy! Again!
  • Is every recursively axiomatizable and consistent theory interpretable in the true arithmetic (TA)?
  • Equations for dual cubic curves

c character assignment

COMMENTS

  1. How to assign char to char* in C?

    That's why assigning a char gives you a warning, because you cannot do char* = char. But the assignment of "H", works, because it is NOT a char - it is a string ( const char* ), which consists of letter 'H' followed by terminating character '\0'. This is char - 'H', this is string ( char array) - "H". You most likely need to change the ...

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

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

  4. C Character Type

    C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.. To represent characters, the computer has to map each integer with a corresponding character using a numerical code. The most common numerical code is ASCII, which stands for American Standard Code for Information Interchange.

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

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

  7. How to Declare and Use Character Variables in C Programming

    Syntax of Declaring Character Variable in C. char variable_name; Here char is used for declaring Character data type and variable_name is the name of variable (you can use any name of your choice for example: a, b, c, alpha, etc.) and ; is used for line terminator (end of line).

  8. Understanding and Working with Char Data Type in C Programming

    Computer. To declare a Char variable in C, you simply use the char keyword, followed by the name of the variable. You can optionally initialize it at the same time. For example: char myChar; // Declaration without initialization. char anotherChar = 'B'; // Declaration with initialization.

  9. C String

    The single characters are surrounded by single quotation marks. The examples below are all chars - even a number surrounded by single quoation marks and a single space is a char in C: 'D', '!', '5', 'l', ' ' Every single letter, symbol, number and space surrounded by single quotation marks is a single piece of character data in C.

  10. Assignment Operators in C

    Assignment Operators in C - In C language, the assignment operator stores a certain value in an already declared variable. ... f = 5; // definition and initializing d and f. char x = 'x'; // the variable x has the value 'x'. Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C ...

  11. Character Pointers and Functions 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 ...

  12. Strings in C

    In C programming String is a 1-D array of characters and is defined as an array of characters. 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][c] = {list of string};Here, var_name is the name of the var

  13. Working with character (char) in C

    However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255. In order to represent characters, the computer has to map each integer with a corresponding character using a numerical code. The most common ...

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

  15. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  16. Structure Assignment (GNU C Language Manual)

    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:

  17. 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:

  18. The C character set

    The C character set, also known as the ASCII character set, is a set of characters that can be used in the C programming language. The term "ASCII" stands for American Standard Code for Information Interchange. Originally developed in the 1960s, ASCII is a widely used character encoding standard that defines numeric codes for various characters.

  19. c

    const char * const p - The pointer p is constant and so are the characters that p points to - i.e. cannot change both the pointer and the contents to what p points to. const char * p - p points to constant characters. You can change the value of p and get it to point to different constant characters. But whatever p points to, you cannot change ...

  20. C++ char Type (Characters)

    ASCII Value. In C and C++, an integer (ASCII value) is stored in char variables rather than the character itself. For example, if we assign 'h' to a char variable, 104 is stored in the variable rather than the character itself. It's because the ASCII value of 'h' is 104.. Here is a table showing the ASCII values of characters A, Z, a, z and 5.

  21. c++

    char a[10] = "Hi"; a = "Hi"; The first is an initialization, the second is an assignment. The first line allocates enough space on the stack to hold 10 characters, and initializes the first three of those characters to be 'H', 'i', and '\0'. From this point on, all a does is refer to the position of the the array on the stack.