Concept
How can you create an array of strings in C?
ComputerScienceOne / Arrays of Strings
"We often need to deal with collections of strings. An array of strings can be viewed as a 2-dimensional character array. Indeed, we’ve seen this before. In the typical C program’s main() function, command line arguments are passed as the second parameter:\n\nint main(int argc, char **argv)\n\nwhich is represented as a double character pointer, char **. Conceptually, each row is a string, char *. The first parameter, argc indicates how many rows there are. The main() function doesn’t need to be told how big each “row” is since strings are null-terminated. We can create our own arrays of strings similar to how we created 2-dimensional arrays of int and double types.\n\n1 //create an array that can hold 5 strings\n\n2 char **names = (char **) malloc(5 * sizeof(char*));\n\n3 int i;\n\n4 for(i=0; i<5; i++) {\n\n5 //each string can hold at most 19 characters\n\n6 names[i] = (char *) malloc(sizeof(char) * 20);\n\n7 }\n\n8 strcpy(names[0], \"Margaret Hamilton\");\n\n9 strcpy(names[1], \"Ada Lovelace\");\n\n10 strcpy(names[2], \"Grace Hopper\");"
Related Ideas
- How can you define arrays of strings in PHP?ComputerScienceOne · Arrays of Strings
- How are arrays of strings used in Java?ComputerScienceOne · Arrays of Strings
- How can you create arrays and collections of strings in Java?ComputerScienceOne · Comparisons
- How can you create static strings with character arrays?ComputerScienceOne · Character Arrays
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How can pointer manipulation create a contiguous two-dimensional array?ComputerScienceOne · Contiguous 2-D Arrays
- How can qsort() sort an array of strings using pointers?ComputerScienceOne · Sorting Pointers to Elements
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory