Home > Software design >  Why does assigning the string in the declaration work but not later?
Why does assigning the string in the declaration work but not later?

Time:11-06

Not sure if I'm phrasing this right, I just want to know why this prints "Johnathan":

#include <stdio.h>
int main()
{
    char personName[20] = "Johnathan";
    printf("%s", personName);
    return 0;
}

while this doesn't:

#include<stdio.h>
int main()
{
    char personName[20];
    personName[20] = "Johnathan";
    printf("%s", personName);
    return 0;
}

I need to be able to assign a string to a declared array (i.e. personName) outside of its first instance.

CodePudding user response:

This declaration

char personName[20] = "Johnathan";

declares a character array that is explicitly initialized by symbols of the string literal "Johnathan".

So the array contains the string that is represented by the string literal.

An alternative declaration can look like

char personName[20] = { "Johnathan" };

In this assignment statement

personName[20] = "Johnathan";

you are trying to initialize the non-existent element personName[20] (the valid range of indices for the array is [0, 19]) of the array personName with the pointer to the first element of the string literal to which the string literal is implicitly converted.

So this statement

printf("%s", personName);

tries to output a non-initiazlied character array that results in undefined behavior.

Also you may not write

personName = "Johnathan";

because arrays do not have the assignment operator.

Instead you could copy elements of the string literal to the array after its declaration the following way

#include <string.h>

//...

strcpy( personName, "Johnathan" );

CodePudding user response:

C’s original development started with simple operations on individual numbers and other data, and these operations translated easily to one or a few processor instructions. It was up to the programmer to write code to perform compound operations, such as copying all elements in an array.

Initializing arrays with strings came later.

Because of C’s development, arrays cannot be used as whole objects in C. You cannot assign one array (like a string literal) to another. Whenever an array is used in an expression, except when we are taking its size (with sizeof) or its address (with &) or are performing certain initializations, the array is automatically converted to a pointer to its first element.

Thus, if we attempt to write personName = "Jonathan";, it fails because personName is not an array after this conversion; so we cannot actually write an assignment that assigns to an array.

Also, in personName[20] = "Jonathan";, the type of personName[20] is a single character; it would be the element with index 20 in the array, if there were one.

We can initialize arrays with string literals in declarations. Initializations use a special form that is not an assignment. In a declaration, the equal sign is not an assignment operator; it is a symbol that starts the list of initial values. Also, initialization only initializes the named object (personName), not an expression made from the extra parts in the declaration (personName[20]). That is part of how declarations differ from expressions. Declarations may have extra parts around the name (called an identifier), like [20] for an array, (…) for functions, and * for pointers, but it is only the named object that is initialized, not the expression made from those extra parts.

To “assign” an array with a new string value, you can use strcpy, as in strcpy(personName, "Jonathan");. The array must have room for the string, including the null character that terminates the string. To declare strcpy, include the line #include <string.h> in your program.

  • Related