0

我正在尝试在 C 中打印一个字符数组,但我无法打印所有内容。我想打印:b1 b2 我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char def[3][10];     //define a multidimensional array of characters 
  strcpy(def[0],"b1"); //insert "b1" at first line
  strcpy(def[1],"b2"); //insert "b2" at first line
  printf("%s",def);    //print everything?
}

上面的代码只打印b1. 我已经尝试过:

printf("%s",def[0]);
printf("%s",def[1]);

但我有错误“无效使用未指定边界的数组”

4

3 回答 3

2
printf("%s", def);

%s conversion specification expects a string. def is an array of strings and not a string.

To print the first string do this:

printf("%s", def[0]);

if you want to print the second string then do this:

printf("%s", def[1]);

and if you want to print both strings:

printf("%s%s", def[0], def[1]);

To print all strings in your array:

for (i = 0; i < sizeof def / sizeof *def; i++)
{
    printf("%s", def[i]); 
}
于 2012-12-15T15:07:58.997 回答
0

您可以通过一次调用将整个多维数组打印char为单个字符串:

printf("%s", (char*) multiDimensionalArray);

因为多维数组的元素是连续的。但是,就像简单的数组一样,printf在第一个终止字符处停止,所以它通常是没有意义的,因为我们几乎总是在每个“行”的末尾有一个终止字符,就像你一样,或者一些未初始化的垃圾。

char def[3][2];

memcpy(def[0], "b1", 2);
memcpy(def[1], "b2", 2);

def[2][0] = '\0';

printf("%s", (char*) def);  // print everything

但是以这种方式使用数组很痛苦,您需要的是对数组进行循环。

(您可以简单地使用*puts打印字符串)

于 2012-12-15T15:42:28.717 回答
0

您首先使用语法初始化数组,就像整个数组获取空值一样。然后执行相同的过程,您可以在输出中获取字符串。

语法:char def[3][10]={};

或者首先定义这个数组,然后通过 bzero 函数使整个数组为零值。

bzero(def,sizeof(def));

您需要在程序中包含 stdlib.h 头文件。

于 2012-12-15T15:39:20.237 回答