创建一个大小为N的数组,然后为每个元素分配值“ []”

时间:2018-12-01 17:57:53

标签: c arrays

我想在C中创建一个数组,然后为该数组中的每个值分配字符串“ []”。


这是我要记住的:

char Array[N];

for(int i = 0; i < N; i++)
{
    Array[i]="[ ]";
}


这样做的正确方法是什么?

4 个答案:

答案 0 :(得分:3)

Bellow是您可以根据自己的喜好自定义的示例工作代码:

#include<stdio.h>
#include<string.h>  // for strcpy: use to copy one string into another

// set a symbolic constant 
#define N  10  

int main(int argc, char **argv)
{
   // declare the array
   char Array[N][4];  // 4, because "[ ]" is 3+1 long

   for(int i=0; i < N; i++){
       strcpy(Array[i], "[ ]");
   }

   // print out the content for test purpose
   for(int i=0; i < N; i++){
       printf("Array[%d] = %s\n", i, Array[i]);
   }

   return 0;
}

答案 1 :(得分:1)

这个问题已经有一个可以接受的解决方案,但是我想提供更多的上下文,这将帮助那些习惯于Java和C ++等高级语言的人理解为什么在用C vs 。

对于初学者来说,并不是每个C编译器都允许您创建一个大小由变量确定的数组(这称为可变长度数组或VLA,您可以在此处了解有关它们的更多信息:How do I declare a variable sized array in C? )。不幸的是,您甚至无法为数组中所需的术语数声明一个const变量(有关更多信息,请参见Can a const variable be used to declare the size of an array in C?)。因此,这就是为什么您不得不在程序中到处键入文字,或者使用我已经演示过的预处理程序命令。

接下来,C语言中的char数组的长度是它可以容纳的char数。但是,由于每个术语的长度为3个字符,最后加上空字符,因此您需要将数组长度比术语数长4倍。您可以使用两个请参见下面的代码以了解如何声明。

最后,您需要#include string.h头文件,以便能够在C语言中使用字符串。

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

int main(){
  #define N_TERMS 6
  #define L_TERM 4
  char term[L_TERM] = "[ ]";
  char Array[N_TERMS * L_TERM] = ""; //array should be the size of the product of number of terms and length of term

  for(int i = 0; i < N_TERMS; i++){
    strcat(Array, term); //strcat adds the second string to the end of the first
  }
  printf("%s", Array); //prints the entire string
  return 0;
}

答案 2 :(得分:0)

一个字符是一个字符。单引号而不是双引号。 “ []”是三个字符。 [,空格和]一起是三个字符。 char数组中的每个索引一次只能容纳一个字符,因此[或空格或]或其他某个字符。

答案 3 :(得分:-1)

首先,您必须

xs :: A

这是代码,因为c中没有字符串,您必须使用char数组来完成

#include <string.h>
相关问题