Skip to content

Instantly share code, notes, and snippets.

@pyk
Created July 5, 2015 00:59
Show Gist options
  • Save pyk/806b43d3f98c4f86c4fe to your computer and use it in GitHub Desktop.
Save pyk/806b43d3f98c4f86c4fe to your computer and use it in GitHub Desktop.
string & list of string in C
#include <stdio.h>
int
main()
{
/* character */
char a;
a = 's';
printf("char a\t= %c\n", a);
/* string is an array of character */
char s1[] = "hello";
printf("s1[]\t= %s\n", s1);
printf("s1[0]\t= %c\n", s1[0]); // h
printf("*(s1)\t= %c\n", *(s1)); // h
printf("*(s1+4)\t= %c\n", *(s1+4)); // o
char s2[] = {'h', 'e', 'l', 'l', 'o', '\0'};
printf("s2[]\t= %s\n", s2);
printf("s2[1]\t= %c\n", s2[0]); // h
printf("*(s2+1)\t= %c\n", *(s2+1)); // e
/* string is a pointer to character */
char *s3 = "hello";
printf("s3\t= %s\t| mem = %d\n", s3, *s3);
printf("s3+1\t= %s\t| mem = %d\n", s3+1, *(s3 + 1)); // ello
printf("*(s3)\t= %c\n", *(s3)); // h
printf("s3[0]\t= %c\n", s3[0]); // h
/* difference: http://stackoverflow.com/a/1704433/3376568*/
/* pointer to "array of character" or
* array of pointer to character is a list of string */
char *s4[2];
s4[0] = "hello";
s4[1] = "world";
printf("*s4[2]\t= %s %s\n", s4[0], s4[1]);
/* pointer to "pointer to character" is a list of string */
char **s5;
s5[0] = "hello";
s5[1] = "world";
printf("**s5\t= %s %s\n", s5[0], s5[1]);
/* array of "array of character" is a list of string */
char s6[2][6] = {{'h', 'e', 'l', 'l', 'o', '\0'}, {'w', 'o', 'l', 'd', '\0'}};
printf("s6[2][6]\t= %s %s\n", s6[0], s6[1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment