BCA Sem 1 | Unit 1 | Computer Concepts & C Programming
Strings in C Language — BKNMU Junagadh
Declaration, Initialization, Memory Allocation, Null Character '\0', and String Functions
string data type. In C, a String is represented as a one-dimensional array of characters terminated by a special Null Character ('\0').
To master strings in C, you must understand three core aspects:
1. Character Array
A sequence of continuous memory locations storing single char values in order.
2. Null Terminator
Signals the end of the string to the C compiler so functions know where to stop reading.
3. String Library
Header file offering built-in functions like strlen(), strcpy(), and strcat().
Memory Allocation for string "BKNMU" in char str[6]:
str[0]
str[1]
str[2]
str[3]
str[4]
str[5]
Notice that a string of 5 characters requires an array size of at least 6 bytes to store the terminating null character '\0'!
Here are the two primary ways to initialize a character array in C:
| Initialization Method | Syntax Example | Null Character Handled By | Description |
|---|---|---|---|
String Literal Method | char str[] = "BKNMU"; | Compiler (Automatically) | Easiest and most common method. Compiler appends '\0'. |
Character List Method | char str[] = {'B','K','N','M','U','\0'}; | Programmer (Manually) | Explicit character array. Must manually append '\0' at the end! |
Fixed Size Allocation | char str[20] = "Junagadh"; | Compiler | Reserves 20 bytes; stores "Junagadh" and fills remaining with '\0'. |
printf("%s", str) keep printing characters starting from index 0 until they encounter '\0'. Without '\0', the program will print garbage characters from adjacent memory!
- Returns string length (excluding
'\0') - Example:
strlen("BKNMU")→5
- Copies source string into destination array
- Overwrites target contents
- Appends (concatenates) source string onto destination
- Modifies destination string
Here is a complete C program demonstrating string creation, input/output, and built-in library functions:
scanf("%s", str) stops reading input as soon as it hits a space! To read strings containing spaces (like full names), use fgets(str, sizeof(str), stdin) instead.
Avoid Unsafe scanf() For Multi-Word Input
Using scanf("%s", str) for "BKNMU Junagadh" will only store "BKNMU".
Use fgets() Function
Use fgets(name, 30, stdin); — it safely reads spaces and prevents buffer overflow.
Avoid Obsolete gets() Function
Never use gets() in modern C as it causes critical memory security vulnerabilities.
'\0'!
- Definition: A string in C is a sequence of characters terminated by a null character (
'\0'). - Null Terminator:
'\0'has an ASCII value of0and signals the end of string data. - Header File: Must include
#include <string.h>to use functions likestrlen,strcpy,strcat,strcmp. - Memory Size: Always allocate
length + 1bytes of storage. - Format Specifier: Use
%sinprintf()andscanf()for string I/O. - strcmp(s1, s2): Returns
0if both strings are identical.