C 打印二维数组

标签 c arrays multidimensional-array printf

我正在尝试使用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/

相关文章:

PHP递归数组使用MYSQL数据

c - 在 c 中使用逗号运算符

c++ - 为什么结构体的 sizeof 不等于每个成员的 sizeof 之和?

c - write系统调用直接把数据写到磁盘?

c - pthread_create() 后的段错误

python - 将 numpy 数组拆分为两个不同大小的子集

javascript - javascript 函数中奇怪的控制台输出数组和 array.pop()

c - 我如何从二维数组中获取每列的总和并将其保存到 C 中的一维数组

python - 带范围的for循环只取最后一个元素

javascript - 在 3D 数组中嵌套 2D 数组时的奇怪行为