One Dimensional Array In C

In a 1D array, we only have a single row of elements. All elements are stored in contiguous memory locations. Now, we will discuss how to declare, initialize, and access array elements.  let’s take a 1D array of size 6.

one dimensional array in c -1D

One Dimensional Array Declaration

When declaring a one-dimensional array in C, the data type can be of any type, and we can assign any name to the array, similar to naming a variable.

 Syntax:

  • Method 01: int arrayName[6]; //arratName is the array name of type integer, and 6 is the size
  • Method 02: int arrayName [];  // this method can’t store input at runtime
  • Method o3:  int arrayName[n]; // define array name at compile time but the size is decided at runtime

One Dimensional Array Initialization

You can initialize an array while declaring it or after declaring it. Various methods of the 1D array for initialization are given below

1. Zero Initialization:

You can initialize all elements of an array to zero using an empty initializer.

int arr[5] = {0}; // arr = {0, 0, 0, 0, 0}

2. Partial Initialization (Missing Values):

If the number of initializers is fewer than the size of the array, the remaining elements are set to zero by default.

int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}

3. Static Initialization with Braces:

You can directly initialize an array with values inside curly braces {}. This is the most common form.

int arr[] = {1, 2, 3, 4, 5};

4. Pointer Array Initialization:

If you’re dealing with an array of pointers, you can initialize an array in the following way

char *arr[3] = {"apple", "banana", "cherry"};
  • *arr dereference the pointer to arr[0] . This is the same as arr[0]. it points the first element of array. similarly,
  • *(arr + 1)  is the same as arr[1].
  • *(arr + 2)  is the same as arr[2].

Note: *arr = arr = arr[0], all these three points to the first element of array.

5. Runtime Initialization using Scanf

Runtime initialization of an array involves assigning values to an array at the time of execution. This method is useful when the size of the array and the values it holds are not known before the program runs.

Code Example:

#include <stdio.h>

int main() {
int n;
printf(“Enter the number of elements: “);
scanf(“%d”, &n);

int arr[n]; // Declaring an array of size n

printf(“Enter %d elements:\n”, n);
for (int i = 0; i < n; i++) {
scanf(“%d”, &arr[i]); // Reading each element into the array
}

printf(“Array elements are: “);
for (int i = 0; i < n; i++) {
printf(“%d “, arr[i]); // Printing elements to verify
}

Issue with Scanf: When using scanf to read strings, limit the number of characters to prevent buffer overflows.

6. Dynamic Initialization using malloc or calloc 

Dynamic initialization involves creating arrays during runtime, but with the ability to allocate memory dynamically using malloc (memory allocation) or calloc (contiguous allocation). These functions are part of the standard C library and allow the program to specify the amount of memory needed during execution. malloc allocates uninitialized memory, while calloc allocates memory and initializes all bits to zero.

Code Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int n;
printf (“Enter the number of elements: “);
scanf(“%d”, &n);

// Using malloc to allocate memory
int *arr = malloc(n * sizeof(int));

printf(“Enter %d elements:\n”, n);
for (int i = 0; i < n; i++) {
scanf(“%d”, &arr[i]); // Reading each element into the dynamically allocated array
}

printf(“Array elements are: “);
for (int i = 0; i < n; i++) {
printf(“%d “, arr[i]); // Printing elements to verify
}

free(arr); // Freeing the allocated memory
return 0;
}

Important:

  • Always verify that malloc or calloc doesn’t return NULL.
  • Memory leaks problem in scanf resolved: free() is a function used in C programming to deallocate memory that has been previously allocated dynamically (using malloc(), calloc(), or realloc()). Its purpose is to return the allocated memory back to the heap to avoid memory leaks.

Accessing Array Element In C 

In a one-dimensional array in C, accessing elements involves using the index of the element. The index is an integer that specifies the position of an element in the array (i.e., the first element is at index 0, the second at index 1, and so on).

You can access array elements using the index in square brackets.

Syntax:

array_name[index]

Method 01: Through Simple Index 

This method uses array indexing, where you directly access array elements using their index. Simple code example is here

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};

// Access and print elements at different indices
printf(“Element at index 0: %d\n”, arr[0]); // 10
printf(“Element at index 1: %d\n”, arr[1]); // 20
printf(“Element at index 2: %d\n”, arr[2]); // 30
printf (“Element at index 3: %d\n”, arr[3]); // 40
printf(“Element at index 4: %d\n”, arr[4]); // 50

return 0;
}

Output:
Element at index 0: 10

Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Method 02: Through Index Pointer

n C, the name of an array is actually a pointer to its first element. You can use pointers and pointer arithmetic to access elements of a one-dimensional array.

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ‘ptr’ points to the first element of the array

// Accessing elements using pointer arithmetic
printf(“Element at index 0: %d\n”, *ptr); // 10
printf(“Element at index 1: %d\n”, *(ptr + 1)); // 20
printf(“Element at index 2: %d\n”, *(ptr + 2)); // 30

return 0;
}

Example using pointers:

Output:
Element at index 0: 10

Element at index 1: 20
Element at index 2: 30

Here, ptr is a pointer to the first element of the array, and we can use pointer arithmetic (*(ptr + n)) to access the elements at index n.

Important: you cau use int *ptr[5] = {10, 20, 30, 40, 50};  instead of after  int *ptr = arr;  to get same results.

Row-Major and Column-Major Orders for 1D Arrays

For a one-dimensional array, row-major and column-major orders are the same because there’s only one row (or one dimension). In this case, elements are stored sequentially in memory, one after the other. The memory layout in both row-major and column-major orders would be:

Example: int arr [5] = {10,20,30,40,50};

Array Name with [Index] Value Memory Address
arr[0] 10 2001
arr[1] 20 2002
arr[2] 30 2003
arr[3] 40 2004
arr[4] 50 2005

1-D array: Address Calculation of Any Element  

A one-dimensional array, also known as a single-dimensional array, is a linear array where elements are accessed using a single index. This index represents either a row or a column position in the array.

Formula:

To calculate the address of a specific element in an array, use this formula:

Address of A[Index] = Base + Size * (Index – LB)

Where:

  • A : Array Name
  • Index: The position of the element whose address is being calculated (not the element’s actual value).
  • Base: The base address of the array (starting address in memory).
  • Size: The storage size of each element in bytes.
  • LB: The lower bound value (default is 0 if not specified).

Question:

Given an array A[500 ………… 800], with:

  • Base address (Base) = 2000
  • Size of each element (Size) = 4 bytes
  • Lower bound (LB) = 500

Find the address of A[750]?

Note: A[500 ………… 800] means, array containing elements from position 500 to 800.

Formula and Calculation:

Address of A[Index] = Base + Size * (Index – LB)
Address of A[750] = 2000 + 4 * (750 – 500)
                              = 2000 + 4 * (250)
                              = 2000 + 1000
Address of A[750] = 3000

Garbage Values in One Dimensional Array (Should Avoid)

In C, garbage values occur when memory is used without being properly initialized. This can happen in several situations, such as with uninitialized local arrays, uninitialized dynamically allocated memory, or improper use of pointers. Garbage values can lead to undefined behavior, crashes, or unpredictable results in a program.

Possibility 01: Uninitialized Arrays

When you declare a local array in C (inside a function), the elements of the array are not automatically initialized. They will contain garbage values unless you explicitly assign values to them.

#include <stdio.h>

int main() {
int arr[5]; // Local array, no initialization

// Accessing elements of arr will lead to garbage values
printf("arr[0] = %d\n", arr[0]); // Garbage value
printf("arr[1] = %d\n", arr[1]); // Garbage value

return 0;
}

Possible Output:

arr[0] = 105287
arr[1] = -48532

Explanation:

  • The array arr is declared but not initialized.
  • Accessing elements arr[0] and arr[1] results in garbage values because they are not assigned any initial values.
  • These values come from whatever data was previously stored in that memory location.

Possibility 01: Out-of-Range Access

Accessing array elements outside the range of the array also leads to undefined behavior and potentially garbage values.

Example Code

#include <stdio.h>

int main() {
int arr[3] = {1, 2, 3}; // Array of size 3

// Accessing out-of-bounds index (arr[3] is out of bounds)
printf(“arr[5] = %d\n”, arr[5]); // Undefined behavior (garbage value)

return 0;
}

Possible Output:

arr[5] = 12345

Solution:

  • Always make sure your array index is within the bounds of the array, i.e., 0 <= index < array_size.
  • If you need bounds checking, ensure the index is valid before accessing the array.

Common Mistakes (Should Avoid)

Mistake01: 
int arr[2] = {10, 20, 30}; // May cause a compiler warning bacuase Too many elements

Mistake02: 
int arr[2];
arr[2] = {10, 20};  // Incorrect inilization