Show List

Arrays and Strings

In C, arrays are used to store multiple values of the same data type. An array is a collection of variables of the same data type that are stored in contiguous memory locations. Arrays are useful when you need to work with multiple values of the same data type.

The general syntax for declaring an array in C is:

css
Copy code
data_type array_name[size];

For example, the following code declares an array of integers named numbers with 5 elements:

python
Copy code
int numbers[5];

You can also initialize an array when you declare it, like this:

python
Copy code
int numbers[5] = {1, 2, 3, 4, 5};

In C, strings are arrays of characters that are terminated by a null character ('\0'). The null character is used to indicate the end of a string.

The general syntax for declaring a string in C is:

scss
Copy code
char string_name[size];

For example, the following code declares a string named name with 10 elements:

scss
Copy code
char name[10];

You can also initialize a string when you declare it, like this:

java
Copy code
char name[10] = "John Doe";

In C, strings can be manipulated using several string functions, such as strcpy(), strcat(), and strlen().

For example, the following code uses the strcpy() function to copy one string to another:

c
Copy code
#include <stdio.h> #include <string.h> int main() { char src[100] = "Hello"; char dest[100]; strcpy(dest, src); printf("Destination string: %s", dest); return 0; }

The output of the above program will be:

go
Copy code
Destination string: Hello



Next: Pointers


    Leave a Comment


  • captcha text