Notes

C - Initialize array of strings

author: Paul Kim

categories: c

tags: c

Initialize array of strings in C

simple initialization of const strings array

#include<stdio.h>

int main() {
  const char *strings[] = {"one","two","three"};

  printf("%s\n", strings[0]);
  printf("%s\n", strings[1]);
  printf("%s\n", strings[2]);

  return 0;
}

example of reading n string inputs

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

int main() {
  int i;
  int n;

  scanf("%d", &n);
  char *strings[n];

  for (i = 0; i < n; i++) {
    char *str = malloc(256 * sizeof(char));
    scanf("%s", str);
    strings[i] = str;
  }

  printf("%s\n", strings[0]);
  printf("%s\n", strings[1]);
  printf("%s\n", strings[2]);

  return 0;
}

// input:
// 3
// a
// bc
// bc

// output:
// a
// bc
// bc

Or we could use pointer arithmetic which does the same thing

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

int main() {
  int i;
  int n;

  scanf("%d", &n);
  char *strings[n];

  for (i = 0; i < n; i++) {
    char *str = malloc(256 * sizeof(char));
    scanf("%s", str);
    *(strings + i) = str;
  }

  for (i = 0; i < n; i++) {
    printf("%s\n", *(strings + i));
  }

  return 0;
}

// input:
// 3
// a
// bc
// bc

// output:
// a
// bc
// bc


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.