我正在尝试使用randomNum
从二维数组中打印字符串。这是我所拥有的:
int randomNum = 0;
char names[2][] = { {"Joe\0"},{"John\0"} };
printf("%s ",names[randomNum][]);
但这不起作用。
最佳答案
这是我认为应该实现的示例代码:
#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);
}
要存储单个字符串,您需要一个 char* 名称(字符指针)。要存储多个字符串,需要使用 char** 名称。这相当于 char* 名称 [NUMBER_OF_STRINGS]。双指针意味着我们创建一个指向内存中具有相同类型指针的空间的指针。换句话说,在本例中它是指向字符串数组的指针。
关于C 打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003120/