Notes

C - Dynamically allocated arrays

author: Paul Kim

categories: c

tags: c

Dynamically allocated arrays in C

In C, we can create arrays like this:

// an array of int of size 10 with initial values of 5
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

// initialize to 1, 2, 0, 0, 0...
int myArray[10] = { 1, 2 };

// all elements 0
int myArray[10] = { 0 };

// this does not initialize all elements to 0 in C
// however, it does in C++
int myArray[10] = {};

We can use the for loop to initialize arrays as well

#include<stdio.h>

int main() {
  int i, a[50];

  for (i = 0; i < 50; i++) {
      a[i] = 5;
  }

  for (i = 0; i < 50; i++) {
      printf("%d ", a[i]);
  }
  printf("\n");

  return 0;
}

But here is an example of dynamically allocating memory to create an array

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

int *dynamicAllocIntArray(int n) {
  int i;
  int *a = malloc(n * sizeof(int));
  for (i = 0; i < n; ++i) {
      *(a + i) = i + 1;
  }
  return a;
}

void printIntArray(const int *a, int n) {
  int i;
  for (i = 0; i < n; ++i) {
      printf("%d ", *(a + i));
  }
  printf("\n");
}

long long factorial(int n) {
  long long f = 1;
  while (n > 0) {
    f *= n;
    n--;
  }
  return f;
}

int main() {
  int n = 3;
  int *a = dynamicAllocIntArray(n);
  printIntArray(a, n);
  free(a);

  printf("%lli\n", factorial(n));

  return 0;
}


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.