I am trying to print a character string from a 2D array using a randomNum
. Here is what I have:
int randomNum = 0;
char names[2][] = { {"Joe\0"},{"John\0"} };
printf("%s ",names[randomNum][]);
This does not work however.
I am trying to print a character string from a 2D array using a randomNum
. Here is what I have:
int randomNum = 0;
char names[2][] = { {"Joe\0"},{"John\0"} };
printf("%s ",names[randomNum][]);
This does not work however.
Here is an example code of what I believe should be implemented:
#include <stdio.h>
#include <stdlib.h>
#define NUMBER_OF_STRINGS 2
int main (int argc, char *argv[])
{
int randomNum = 0;
/* The capacity of the array is to hold up to 2 strings*/
char *names[NUMBER_OF_STRINGS] = { "Joe",
"John"};
/*
*
* names[0][0] = 'J' -> first element of names[0] - J
* names[0][1] = 'o' -> second element of names[0] - o
* names[0][2] = 'e' -> third element of names[0] - e
*
* names[1][0] = 'J' -> first element of names[0] - J
* names[1][1] = 'o' -> second element of names[0] - o
* names[1][2] = 'h' -> third element of names[0] - h
* names[1][3] = 'n' -> third element of names[0] - n
*
*/
/*Here we pass the pointer of the array of strings and we index the first string*/
printf("%s \n", names[randomNum]);
/*Here is how to access each of the elements separetly*/
printf("Here we print the name Joe character by character\n");
printf("%c\n", names[0][0]);
printf("%c\n", names[0][1]);
printf("%c\n", names[0][2]);
printf("Here we print the name John character by character\n");
printf("%c\n", names[1][0]);
printf("%c\n", names[1][1]);
printf("%c\n", names[1][2]);
printf("%c\n", names[1][3]);
return (0);
}
To store a single string you need a char* name (character pointer). To store multiple strings it is required to use a char** names. Which is equivalent to char* names [NUMBER_OF_STRINGS]. The double pointer means that we create a pointer to a space in the memory which has a pointer of the same type. In other words in this case it is the pointer to the array of strings.