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

まず、配列全体がnull値になるように、次のような構文で配列を初期化します。次に、出力で文字列を取得できるのと同じ手順を実行します。

構文:char def [3] [10] = {};

or first define this array and then by bzero function make whole array to zero value.

bzero(def,sizeof(def));

you need to include stdlib.h header file in your program.

于 2012-12-15T15:39:20.237 に答える
0

You could print a whole multi-dimensional array of char as a single string, with a single call:

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

Because elements of a multi-dimensional array are contiguos. But, exactly as simple arrays, printf stops at the first termination character, so it's usually pointless because we almost always have a termination character at the end of each "row" just like you, or some uninitialized garbage.

char def[3][2];

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

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

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

But use arrays this way is painful, what you need is a loop over the array.

(you can simply use *puts to print strings)

于 2012-12-15T15:42:28.717 に答える