- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

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.
Assigning strings to arrays of characters
I am a little surprised by the following.
I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
10 Answers 10
When initializing an array, C allows you to fill it with values. So
is basically the same as
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array. This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy .
- 9 Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy. – dwc Feb 23, 2009 at 23:01
- 4 Also, s should be const char*, not char*. – aib Feb 24, 2009 at 14:17
- 1 s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm'; works if one wants to replace the string characters one by one even after initialization. – RBT Oct 28, 2016 at 2:44
- @RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error – shoosh Dec 4, 2016 at 7:52
- 1 @dwc there is no problem with strcpy(), just make sure your buffer is long enough for the input string – 12431234123412341234123 Jan 18, 2017 at 10:16
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char , terminated by a null character \0 . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x[] = {'h','e','l','l','o','\0'};
The correct way would be:
or better yet:
- 2 Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922 – nucleon Feb 23, 2017 at 10:40
- I think this approach could easily be recommended – Volt Oct 12, 2018 at 8:00
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did.
At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.

- Why do you need 100 bytes for hello? Isn't char s[6] enough? – mLstudent33 Feb 9, 2020 at 20:28
- 2 @mLstudent33, it was the example given by the OP. – Matt Davis Feb 10, 2020 at 14:18
To expand on Sparr's answer
Think of it like this:
Imagine that there are 2 functions, called InitializeObject , and AssignObject . When the compiler sees thing = value , it looks at the context and calls one InitializeObject if you're making a new thing . If you're not, it instead calls AssignObject .
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
Note that you can still do:
- It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally. – Chris Lutz Feb 24, 2009 at 14:33
- Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs. – aib Feb 24, 2009 at 14:47
- I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense. – aib Feb 24, 2009 at 14:49
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name of the array is actually a pointer to the first element of the array. (Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator )
To copy a string literal (such as "Hello world" or "abcd" ) to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
I am annoyed by this... It really would be logical if:
should give the same result as:
But I guess it just doesn't work like that. Anyways, here was my workaround:
its almost as good, because it is short.
Strangely enough, another thing which has worked for me (though a little off-topic perhaps) is when you declare arrays of structs, you can initialize them with the good-ole double quotes like this:
Incidentally, this method of initialization is known as a "compound literal" Id love to see if anyone could explain why this works to use double quotes and not the string = "hello"; way...
This method is great if you have a lot of strings by the way, because it allows you to write code like:
Or if you're going to go all multilingual for some app:
You can use this:
Where yylval is char*. strdup from does the job.

- strdup from <string.h> does the job :) – Yekatandilburg Jul 21, 2015 at 2:31
- strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done – JoshKisb Mar 1, 2019 at 14:13
What I would use is

- 2 Most of us wouldn't, because it risks undefined behaviour. The above is only safe for const char* . – Toby Speight Apr 8, 2016 at 13:21
Your Answer
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 , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Copyright issues when journal is defunct
- What video game is Charlie playing in Poker Face S01E07?
- Chord III is rarely used, but Pachelbel's Canon in D has F#m
- Acidity of alcohols and basicity of amines
- Lots of pick movement
- Theoretically Correct vs Practical Notation
- Is it possible to create a concave light?
- If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law?
- How can I download installation file for GRASS 7.2.0?
- Recovering from a blunder I made while emailing a professor
- Tips for golfing in SVG
- Is there any way to orbit around the object instead of a 3D cursor?
- Stored Procedure Tuning Help
- How can I explain to my manager that a project he wishes to undertake cannot be performed by the team?
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- What did Ctrl+NumLock do?
- Can I tell police to wait and call a lawyer when served with a search warrant?
- Kinetic rotational energy at different rotational axis
- Is there a proper earth ground point in this switch box?
- Spacing in tuplets (in sheet-music)
- Partner is not responding when their writing is needed in European project application
- Largest Binary Area
- Can I use rigid metal 90s with flex duct?
- Mathematica not solving this integral
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Arrays in C/C++
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- std::sort() in C++ STL
- Bitwise Operators in C/C++
- Core Dump (Segmentation fault) in C/C++
- Multidimensional Arrays in C / C++
- Left Shift and Right Shift Operators in C/C++
- Substring in C++
- Converting Strings to Numbers in C/C++
- rand() and srand() in C++
- Different Methods to Reverse a String in C++
- What is Memory Leak? How can we avoid?
- Command line arguments in C/C++
- Enumeration (or enum) in C
- std::string class in C++
- Function Pointer in C
- fork() in C
- C Language Introduction
- Strings in C
- Data Types in C
- Structures in C
- Power Function in C/C++
- INT_MAX and INT_MIN in C/C++ and Applications
- Taking String input with space in C (4 Different Methods)
- Modulo Operator (%) in C/C++ with Examples
- Pointer to an Array | Array Pointer
- Memory Layout of C Programs
- Static Variables in C
- TCP Server-Client implementation in C
Array of Strings in C
- Difficulty Level : Medium
- Last Updated : 02 Dec, 2022
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.
- var_name is the name of the variable in C.
- r is the maximum number of string values that can be stored in a string array.
- c is a maximum number of character values that can be stored in each string array.
Example:
Below is the Representation of the above program
We have 3 rows and 10 columns specified in our Array of String but because of prespecifying, the size of the array of strings the space consumption is high. So, to avoid high space consumption in our program we can use an Array of Pointers in C.
Invalid Operations in Arrays of Strings
We can’t directly change or assign the values to an array of strings in C.
Here, arr[0] = “GFG”; // This will give an Error which says assignment to expression with an array type.
To change values we can use strcpy() function in C
Array of Pointers of Strings
In C we can use an Array of pointers. Instead of having a 2-Dimensional character array, we can have a single-dimensional array of Pointers. Here pointer to the first character of the string literal is stored.
Below is the C program to print an array of pointers:
Please Login to comment...
- simmytarika5
Improve your Coding Skills with Practice
Start your coding journey now.

Strings Array in C

What is an Array of String?
The string is a collection of characters, an array of a string is an array of arrays of characters. Each string is terminated with a null character. An array of a string is one of the most common applications of two-dimensional arrays.
scanf( ) is the input function with %s format specifier to read a string as input from the terminal. But the drawback is it terminates as soon as it encounters the space. To avoid this gets( ) function which can read any number of strings including white spaces.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Sting is an array of characters terminated with the special character known as the null character (“\0”).

The syntax for array of string is as follows:
Str_name is the string name and the size defines the length of the string (number of characters).
A String can be defined as a one-dimensional array of characters, so an array of strings is two –dimensional array of characters.
Alternatively, we can even declare it as
From the given syntax there are two subscripts first one is for how many strings to declare and the second is to define the maximum length of characters that each string can store including the null character. C concept already explains that each character takes 1 byte of data while allocating memory, the above example of syntax occupies 2 * 6 =12 bytes of memory.
0 1 2 3 4 5 6 7 Index
Variables 2000 2001 2002 2003 2004 2005 2006 2007 Address
This is a representation of how strings are allocated in memory for the above-declared string in C.
Each character in the string is having an index and address allocated to each character in the string. In the above representation, the null character (“\0”) is automatically placed by the C compiler at the end of every string when it initializes the above-declared array. Usually, strings are declared using double quotes as per the rules of strings initialization and when the compiler encounters double quotes it automatically appends null character at the end of the string.
From the above example as we know that the name of the array points to the 0th index and address 2000 as we already know the indexing of an array starts from 0. Therefore,
As the above example is for one-dimensional array so the pointer points to each character of the string.
Examples of Array String in C
Following are the examples:

Now for two-dimensional arrays, we have the following syntax and memory allocation. For this, we can take it as row and column representation (table format).
In this table representation, each row (first subscript) defines as the number of strings to be stored and column (second subscript) defines the maximum length of the strings.
From the above example as we know that the name of the array points to the 0th string. Therefore,
str_name + 0 points to 0th string “gouri”
str_name + 1 points to 1st string “ram”
As the above example is for two-dimensional arrays so the pointer points to each string of the array.

Functions of strings
strcpy(s1,s2); this function copies string s2 innto sting s1.
strcat(s1,s2); this function concatenates strings s1 and s2 , string s2 is appended at the end of the string s1.
strlen(s1); this function returns the length of the string s1.
strcmp(s1,s2); This function compares both strings s1 and s2.
strchr(s1, ch); these functions find the first occurrence of the given character ch in the string s1 and the pointer points to this character in the string.
strstr(s1,s2); this finds the first occurrence of string s2 in the string s1 and the pointer points to the string s2 in the string s1.
With some invalid operations are str_arr[0] = “gouri”; in this operation pointer of the string is assigned to the constant pointer which is invalid and is not possible, because the name of the array is a constant pointer.
To avoid this we can assign str_arr by using strcpy(str_arr[0],”gouri”).
Conclusion – Strings Array in C
An array itself defines as a list of strings. From the above introduction, we can conclude that declaration and initialization of strings are different as we saw for every string the compiler appends null character when it reads the string as input. There are many string handling functions a few functions with examples are explained above. Therefore arrays of the string are as easy as arrays.
Recommended Articles
This is a guide to a Strings Array in C. Here we discuss the basics of the Array Strings, Example of Array String in C and Functions of strings. You can also go through our other suggested articles to learn more–
- String Array in C#
- Multidimensional Array in C
- 2D Arrays in C#
- String in C

Related Courses

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept
By signing up, you agree to our Terms of Use and Privacy Policy .
Forgot Password?
This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Explore 1000+ varieties of Mock tests View more
Submit Next Question

C Programming Tutorial
- Array of Strings in C
Last updated on July 27, 2020
What is an Array of Strings? #
It is important to end each 1-D array by the null character, otherwise, it will be just an array of characters. We can't use them as strings.
Declaring an array of strings this way is rather tedious, that's why C provides an alternative syntax to achieve the same thing. This above initialization is equivalent to:
We already know that the name of an array is a pointer to the 0th element of the array. Can you guess the type of ch_arr ?
The ch_arr is a pointer to an array of 10 characters or int(*)[10] .
Therefore, if ch_arr points to address 1000 then ch_arr + 1 will point to address 1010 .
From this, we can conclude that:
ch_arr + 0 points to the 0th string or 0th 1-D array. ch_arr + 1 points to the 1st string or 1st 1-D array. ch_arr + 2 points to the 2nd string or 2nd 1-D array.
In general, ch_arr + i points to the ith string or ith 1-D array.

From this we can conclude that:
*(ch_arr + 0) + 0 points to the 0th character of 0th 1-D array (i.e s ) *(ch_arr + 0) + 1 points to the 1st character of 0th 1-D array (i.e p ) *(ch_arr + 1) + 2 points to the 2nd character of 1st 1-D array (i.e m )
In general, we can say that: *(ch_arr + i) + j points to the jth character of ith 1-D array.
Note that the base type of *(ch_arr + i) + j is a pointer to char or (char*) , while the base type of ch_arr + i is array of 10 characters or int(*)[10] .
To get the element at jth position of ith 1-D array just dereference the whole expression *(ch_arr + i) + j .
The following program demonstrates how to print an array of strings.
Expected Output:
Some invalid operation on an Array of string #
It allocates 30 bytes of memory. The compiler will do the same thing even if we don't initialize the elements of the array at the time of declaration.
We already know that the name of an array is a constant pointer so the following operations are invalid.
Here we are trying to assign a string literal (a pointer) to a constant pointer which is obviously not possible.
To assign a new string to ch_arr use the following methods.
Let's conclude this chapter by creating another simple program.
Expected Output: 1st run:
How it works:
The program asks the user to enter a name. After the name is entered it compares the entered name with the names in the master_list array using strcmp() function. If match is found then strcmp() returns 0 and the if condition strcmp(name, master_list[i]) == 0 condition becomes true. The variable found is assigned a value of 1 , which means that the user is allowed to access the program. The program asks the user to enter a number and displays the factorial of a number.
If the name entered is not one of the names in the master_list array then the program exits by displaying an error message.
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
- Character Array and Character Pointer 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
- 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.

Declaring and Initializing a string variables:
String input and output:.
%s format specifier to read a string input from the terminal.
But scanf() function, terminates its input on the first white space it encounters.
edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.
The gets() function can also be used to read character string with white spaces
String Handling Functions:
C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.
strcat() function in C:

strcat() 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.

Example of strcpy() function:
StudyTonight
strrev() function:
It is used to reverse the given string expression.

Code snippet for strrev() :
Enter your string: studytonight Your reverse string is: thginotyduts
Related Tutorials:
- ← Prev
- Next →

C Programs
c interview tests.

Geek Culture

Jul 13, 2021
String — An array of characters with ‘\0’
N umbers and characters can be stored in an array. What if a word or a sentence is needed to be stored in a variable? One way to do this is using a character array. There is a more convenient way, to store them as strings.
What is a string?
A string is an array of characters that is terminated with a null terminator. The null terminator is a special character ‘\0’, which has the numerical value of 0. It is used to represent emptiness. So, in the case of a string, the null terminator denotes where the string ends. So, can’t we just use an empty char to terminate? No, char cannot accept empty values. It does not work like that. That is why a null terminator is used.
This is how to store a sentence or a word using a char array. Now, think what if there is a need to display the whole sentence. The way is to create a for loop and loop through each char and display them. This is inconvenient when working with many words or when you need to compare whether two strings are equal.
A string is stored like a char except for the ‘\0’ at the end. A string can be displayed using the “%s” format specifier . Now, the looping of the array is not needed to display the whole sentence. This is the actual format of the strings but declaring strings is easier.
This too gives the same output. While declaring a string like this, the string is converted to a char array and terminated with ‘\0’ behind the scenes. So, it’s cool.
Comparing strings
To compare strings, we need to include ‘string.h’.
This header file provides some functions or ways to do some operations on strings. The ‘strcmp()’ is used to compare strings.
Within the parentheses of the ‘strcmp()’, the strings to be compared are provided. This outputs 0 if the strings are equal and some other values if the strings are not equal.
Assigning to a string
String assignment does not work in the usual way.
The error says we are trying to assign to an expression with an array type. Basically, a string is an array of characters. So, we have to make a loop to assign each item of the myCar array to the item of myNewChar array. We cannot assign it directly. We need to use a function from ‘string.h’ that is strcpy().
To assign a string to another string pass the destination string and the source string in the order, ie strcpy(destination string, source string).
Reading strings
Reading string input from the user is a bit different.
Usually, an ampersand is placed before the variable to which the input value is to be stored.
For strings, the ampersand is not needed. The reason for this is beyond the scope of this article. You can search about it if you are interested.
This is how to read strings. It works fine for words without spaces. In sentences and full names, there will be spaces.
If the name is one word like ‘Shafi’, it outputs “Shafi”. If the name contains space like “Shafi Sahal”, still the output will be “Shafi”. What happened here is that while reading the input, the reading stopped at the first occurrence of the space in the string.
To read strings with spaces, there is more than one way. Here, we will be discussing the way by using the scanset. You can check other ways if you are interested. You may also check what is a scanset?
Here, instead of a format specifier , the scanset is given. The scanset tells how to read the input. The scanset is given between the square brackets: %[], in this case, the scanset is “^\n”. This tells to read the input until a newline is encountered. So, until the enter key is pressed, the whole sentence or words will be taken as the input.
Sample Quiz Program
Let’s make a small quiz program from all the knowledge we acquired through this and previous articles.
Previous => Arrays — store multiple items using the same variable.
Next => Functions — Reusable Logic
More from Geek Culture
A new tech publication by Start it up (https://medium.com/swlh).
About Help Terms Privacy
Get the Medium app

Shafi Sahal
Developer, adventure lover and a truth seeker. Like to write about topics from a unique perspective. Twitter: https://twitter.com/_shafisahal .
Text to speech

Strings in C: How to Declare & Initialize a String Variables in C
What is string in c.
A String in C is nothing but a collection of characters in a linear sequence. ‘C’ always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks.
‘C’ provides standard library <string.h> that contains many functions which can be used to perform complicated operations easily on Strings in C.
In this tutorial, you will learn-
- How to Declare and Initialize a String in C
C String Input: C Program to Read String
C string output: c program to print a string, fputs() function, puts function, the string library, converting a string to a number, how to declare a string in c.
The classic Declaration of strings can be done as follow:
The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are going to be stored inside the string variable in C. Some valid examples of string declaration are as follows,
The above example represents string variables with an array size of 15. This means that the given C string array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL character ‘\0’ to the character array created.
How to Initialize a String in C?
Let’s study the String initialization in C. Following example demonstrates the initialization of Strings in C,
In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks.
‘C’ also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way,
The name of Strings in C acts as a pointer because it is basically an array.
When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the “%s” format specifier without using the “&” to access the variable address because an array name acts as a pointer. For example:
Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example:
The fgets() arguments are :
- the string name,
- the number of characters to read,
- stdin means to read from the standard input which is the keyboard.
The standard printf function is used for printing or displaying Strings in C on an output device. The format specifier used is %s
String output is done with the fputs() and printf() functions.
The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen. For example:
The puts function is used to Print string in C on an output device and moving the cursor back to the first position. A puts function can be used in the following way,
The syntax of this function is comparatively simple than other functions.
The standard ‘C’ library provides various functions to manipulate the strings within a program. These functions are also called as string handlers. All these handlers are present inside <string.h> header file.
Lets consider the program below which demonstrates string library functions:
Other important library functions are:
- strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
- strncpy(str1, str2, n) This function is used to copy a string from another string. Copies the first n characters of str2 to str1
- strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if character not found.
- strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c in str1, or NULL if character not found.
- strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found.
- strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1 and returns a pointer to str1.
- strlwr() :to convert string to lower case
- strupr() :to convert string to upper case
- strrev() : to reverse string
In C programming, we can convert a string of numeric characters to a numeric value to prevent a run-time error. The stdio.h library contains the following functions for converting a string to a number:
- int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first character is not a number or no numbers are encountered.
- double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is returned if the first character is not a number or no numbers are encountered.
- long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer value. 0 is returned if the first character is not a number or no numbers are encountered.
The following program demonstrates atoi() function:
- A string pointer declaration such as char *string = “language” is a constant and cannot be modified.
- A string is a sequence of characters stored in a character array.
- A string is a text enclosed in double quotation marks.
- A character such as ‘d’ is not a string and it is indicated by single quotation marks.
- ‘C’ provides standard library functions to manipulate strings in a program. String manipulators are stored in <string.h> header file.
- A string must be declared or initialized before using into a program.
- There are different input and output string functions, each one among them has its features.
- Don’t forget to include the string library to work with its functions
- We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes.
- We can manipulate different strings by defining a array of strings in C.
You Might Like:
- C Tokens, Identifiers, Keywords: What is Tokens & Its Types
- Bitwise Operators in C: AND, OR, XOR, Shift & Complement
- Dynamic Memory Allocation in C using malloc(), calloc() Functions
- calloc() Function in C Library with Program EXAMPLE
- realloc() Function in C Library: How to use? Syntax & Example

C# Tutorial
C# examples, create an array.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets :
We have now declared a variable that holds an array of strings.
To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:
To create an array of integers, you could write:
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in cars :
Try it Yourself »
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
Array Length
To find out how many elements an array has, use the Length property:
Other Ways to Create an Array
If you are familiar with C#, you might have seen arrays created with the new keyword, and perhaps you have seen arrays with a specified size as well. In C#, there are different ways to create an array:
It is up to you which option you choose. In our tutorial, we will often use the last option, as it is faster and easier to read.
However, you should note that if you declare an array and initialize it later, you have to use the new keyword:
C# Exercises
Test yourself with exercises.
Create an array of type string called cars .
Start the Exercise

COLOR PICKER

Get certified by completing a course today!

Certificates
Report error.
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.

IMAGES
VIDEO
COMMENTS
Whether in the form of a fizzy drink or flavored lozenges, cold and flu preventative supplements almost always highlight vitamin C as one of their key ingredients. So, what’s so magical about vitamin C? Also known as ascorbic acid, vitamin ...
Hepatitis C, a virus that attacks the liver, is a tricky disease. Some people have it and may never know it as they are affected by any sorts of symptoms. It can remain silent until there is severe damage to your liver.
Hansen Communication Lab developed the concept of the five C’s of communication, which are the following: articulate clearly; speak correctly; be considerate; give compliments; and have confidence.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn
Array of Strings in C · Syntax: char variable_name[r] = {list of string}; · Example: Below is the Representation of the above program · Example:
#define MAX_STRING_SIZE 40 char arr[][MAX_STRING_SIZE] = { "array of c string", "is fun to use", "make sure to properly", "tell the array size" };. But it is a
#include <iostream> · int main() { · char array[] = "Hello, world!\n"; · char *cp = array; · const char *ccp = cp; · std::cout << ccp;. } · }.
datatype name_of_the_array [ ] = { Elements of array }; char str_name[8] = "Strings";. Str_name is the string name and the size defines the length of the string
C swap values of two variables · C Programming Full Course for free 🕹️ · Character arrays and pointers - part 1 · Reversing Strings (in C) and
The first subscript of the array i.e 3 denotes the number of strings in the array and the second subscript denotes the maximum length of the string. Recall the
String is a sequence of characters that is treated as a single data item and terminated by null character \0. In C languae strings are not supported hence
main.c:16:11: error: assignment to expression with array type.
A C String is a simple array with char as a data type. 'C' language does not directly support string as a data type. Hence, to display a String
To declare an array, define the variable type with square brackets: string[] cars;. We have now declared a variable that holds