String Basics in C

In this tutorial, you will learn about strings in C, their usage, the ways to declare and initialize them.

In C, a string is are an array of Data Type char, ended by a null char ‘\0’.

char name[5] = { 'F', 'R', 'E', 'D', '\0' };
char name[] = { 'F', 'R', 'E', 'D', '\0' };

String declaration and initialization in C

Below are the ways to declare and initialize a string in C:

char name[] = "FRED";
char name[5] = "FRED";
char name[] = {'F', 'R', 'E', 'D', '\0'};
char name[5] = {'F', 'R', 'E', 'D', '\0'};

Note that the variable name[] and name[5] do not require the null character at the end of it, whereas the arrays do require the null character

String assignment in C

Unlike most programming languages,  a string in C can only be assigned during its declaration. Once a string is declared, it can not be assigned or reassigned.

For example, the code below will throw an error

char name[] = "Fred";
name = 'Charles';

error: assignment to expression with array type

Passing strings to functions

Strings can be passed to a function as an argument/parameter. The arguments should have the form of an array of char. For example:

void PrintString( char myString[])

is a signature of a void function that takes a string variable (string array of char Data Type) as an argument.

Example of passing a string to a function

#include <stdio.h>
void PrintString (char myString[])
{
  printf ("%s", myString);
}

int main()
{

  char string[] = "CodingPanel.com";

  PrintString (string);

  return 0;
}

CodingPanel.com

Summary

  • Strings in C are arrays of char Data Type
  • String array is terminated by a null char ‘\0’
  • String in C cannot be reassigned a value
Back to: Learn C Programming > Strings in C

Leave a Reply

Your email address will not be published. Required fields are marked *