top of page
Writer's picturecompnomics

Array Creation and Initialization in C

Here are two ways to create a static int array and initialize it in C:

Method 1: Using initializer list:

#include <stdio.h>

int main() {
  // Static array with size 5 and initialized with values
  int my_array[5] = {1, 2, 3, 4, 5};

  // Print the array elements
  for (int i = 0; i < 5; i++) {
    printf("%d ", my_array[i]);
  }
  printf("\n");

  return 0;
}

This code declares a static integer array my_array of size 5 and initializes it with values {1, 2, 3, 4, 5} using an initializer list within the square brackets. This method works for any fixed size and known values at compile time.

Method 2: Using explicit value assignment:

#include <stdio.h>

int main() {
  // Static array with size 5
  int my_array[5];

  // Initialize each element with a value
  my_array[0] = 10;
  my_array[1] = 20;
  my_array[2] = 30;
  my_array[3] = 40;
  my_array[4] = 50;

  // Print the array elements
  for (int i = 0; i < 5; i++) {
    printf("%d ", my_array[i]);
  }
  printf("\n");

  return 0;
}

This code declares a static integer array my_array of size 5 without initialization initially. Then, it assigns specific values to each element manually inside the main function. This method allows for more flexibility in assigning values if they are not known beforehand.

Remember that static arrays have fixed size throughout the program execution and are initialized only once before the main function starts. They retain their values throughout the program. Choose the method that best suits your initialization needs and desired behaviour.

43 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page