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

Ree's user avatar

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 .

Charles Moonen's user avatar

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:

H.S.'s user avatar

Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

Sparr's user avatar

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.

Neuron's user avatar

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

Community's user avatar

Note that you can still do:

aib's user avatar

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!

JMS Creator's user avatar

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:

Leigh Boyd's user avatar

You can use this:

Where yylval is char*. strdup from does the job.

josliber's user avatar

What I would use is

Toby Speight's user avatar

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 .

Hot Network Questions

assign value to string array in c

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 .

Related Articles

Array of 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.

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

Improve your Coding Skills with Practice

Start your coding journey now.

EDUCBA

Strings Array in C

Priya Pedamkar

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”).

Course Curriculum

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:

string array in c

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.

string array in c

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–

Sale

Related Courses

EDUCBA

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

Quiz

Explore 1000+ varieties of Mock tests View more

Submit Next Question

quiz

C Programming Tutorial

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.

assign value to string array in c

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

Ezoic

Recent Posts

C Syntax Rules

C Functions

C Structures

C File/Error

String and Character Array

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

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

C Function Calls

C Variables

C Datatypes

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

string in C

Declaring and Initializing a string variables:

String input and output:.

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

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

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

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

String Handling Functions:

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

The following are the most commonly used string handling functions.

strcat() function in C:

strcat() function in C

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

strlen() and strcmp() function:

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

strcpy() function:

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

srtcpy() function in C

Example of strcpy() function:

StudyTonight

strrev() function:

It is used to reverse the given string expression.

strrev() function in C

Code snippet for strrev() :

Enter your string: studytonight Your reverse string is: thginotyduts

Related Tutorials:

Studytonight Coding course Ad

  C Programs

  c interview tests.

Geek Culture

Geek Culture

Shafi Sahal

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

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

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

Guru99

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-

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

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:

The following program demonstrates atoi() function:

You Might Like:

assign value to string array in c

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

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get certified by completing a course today!

Subscribe

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

  1. Java String Array- Tutorial With Code Examples

    assign value to string array in c

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

    assign value to string array in c

  3. Declare String In C

    assign value to string array in c

  4. C# String Array [Explained with 4 Examples]

    assign value to string array in c

  5. Array of Strings in C [ Programs with Explanation ]

    assign value to string array in c

  6. 😀 Assign value to string python. Python: assign a value to dictionaries. 2019-03-01

    assign value to string array in c

VIDEO

  1. 05 Data Structures Introduction and Array

  2. How to Assign and Re-assign Values to Arrays in C++

  3. C# Tutorial for Beginners 19 : ArrayList

  4. C# ArrayList

  5. Session

  6. Variables in Python-python programming for beginners

COMMENTS

  1. Everything You Need to Know About Vitamin C

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

  2. Signs and Symptoms of Hepatitis C

    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.

  3. What Are the Five C’s of Communication?

    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.

  4. Assigning strings to arrays of characters

    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

  5. Array of Strings in C

    Array of Strings in C · Syntax: char variable_name[r] = {list of string}; · Example: Below is the Representation of the above program · Example:

  6. Array Of C String

    #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

  7. Can we assign a string to a char array in C?

    #include <iostream> · int main() { · char array[] = "Hello, world!\n"; · char *cp = array; · const char *ccp = cp; · std::cout << ccp;. } · }.

  8. Strings Array in C

    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

  9. C array of strings

    C swap values of two variables · C Programming Full Course for free 🕹️ · Character arrays and pointers - part 1 · Reversing Strings (in C) and

  10. Array of Strings in C

    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

  11. String and Character Arrays in C Language

    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

  12. String

    main.c:16:11: error: assignment to expression with array type.

  13. Strings in C: How to Declare & Initialize a String Variables in C

    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

  14. C# Arrays

    To declare an array, define the variable type with square brackets: string[] cars;. We have now declared a variable that holds