我正在尝试使用print a # a=10
print b # b=10
print c # c=10
从2D阵列打印字符串。这是我所拥有的:
randomNum
但这不起作用。
答案 0 :(得分:0)
以下是我认为应该实现的示例代码:
#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]。双指针意味着我们创建了一个指向内存中具有相同类型指针的空间的指针。换句话说,在这种情况下,它是指向字符串数组的指针。