Computer Science

C Program — Arrays & Strings

2023-08-13 2 min read

Array

A variable holds a single value, but storing many values one by one quickly gets tedious.

For example, to record three students’ scores:

Declare

DataType  arrayName[size]  =  { values };

Array Input/Output

Two-dimensional Arrays

An array whose elements are themselves arrays.

Declare

DataType  arrayName[column][row]  =  { {values}, {values} };

Two-dimensional Arrays Input/Output

String

Strings

C has no dedicated string type, so a string is represented as a char array:

…or, alternatively, as a pointer:

Declare

char  name[size]  =  {'d', 'a', 't', 'a'};

char  name[size]  =  "data";

Gets/Fgets/Puts

String input / output.

gets doesn’t know the size of the char array — it only stops at a newline or EOF — so it can cause a buffer-overflow security problem.

Scanf

String functions

There are many important string functions defined in the string.h library.

Strlen

strlen() returns the length of the given string. It doesn’t count the null character '\0'.

Strcpy

strcpy(destination, source) copies the source string into destination.

Strcat

strcat(first_string, second_string) concatenates two strings; the result is returned in first_string.

Strcmp

strcmp(first_string, second_string) compares two strings and returns 0 if they are equal.

Strrev

strrev(string) returns the reverse of the given string.

Strlwr

strlwr(string) returns the string in lowercase.

Strupr

strupr(string) returns the string in uppercase.

Strstr

strstr() returns a pointer to the first occurrence of the match string within the given string. It returns the substring from that first match to the end of the string.

← Posts
meow~