Char Arrays and Literals in C

Learn about char arrays and character literals in C programming. Understand how to declare, initialize, and use them with examples on Debian 12 using Vim.

Char Arrays and Literals in C Programming

In C, char arrays are used to store sequences of characters, typically for strings. Character literals represent single characters enclosed in single quotes.

Declaring Char Arrays

Syntax:

char arrayName[size];

Example:

char name[6];

Initializing Char Arrays

You can initialize with individual characters or string literals.

char name[6] = 'V', 'l', 'a', 'd', '!', '\\0';
char name[] = \\"Vlad!\\";

Character Literals

Single characters in single quotes:

char letter = 'A';

Strings and Null Terminator

Strings in C end with a null character '\\0' to mark the end.

This is automatic if you initialize with a string literal.

Example Program

#include 

int main() 
    char greeting[] = \\"Hello\\";
    char letter = 'A';

    printf(\\"Greeting: %s\\\
\\", greeting);
    printf(\\"First letter: %c\\\
\\", letter);

    return 0;

Compile and Run

gcc char_array.c -o char_array
./char_array

Expected Output

Greeting: Hello
First letter: A

Summary

Char arrays store strings as sequences of characters, ending with a null character. Character literals represent single characters.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/char-arrays-and-literals-in-c/?feed_id=13195&_unique_id=689654f88eed9

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

How to make a skybox in Three.js: A perfect guide

A Complete Roadmap for Becoming a Back-end Developer