I would like to create an array in C and then assign to every value in that array the string "[ ]".
This is what I have in mind:
char Array[N];
for(int i = 0; i < N; i++)
{
Array[i]="[ ]";
}
What is the correct approach to doing that?
I would like to create an array in C and then assign to every value in that array the string "[ ]".
char Array[N];
for(int i = 0; i < N; i++)
{
Array[i]="[ ]";
}
Bellow is a sample working code you customize to your taste:
#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;
}
This question already has an accepted solution but I'd like to provide a bit more context that will help people who are used to higher-level languages like Java and C++ understand why these steps are needed when writing this algorithm in C vs. in a newer language.
For starters, not every C compiler will allow you to create an array with a size determined by a variable (this is called a Variable Length Array, or VLA--you can read more about them here: How do I declare a variable sized array in C?). Unfortunately you can't even declare a const variable for the number of terms you want in your array (read more about that here: Can a const variable be used to declare the size of an array in C?). So that's why you're stuck typing the literals everywhere in the program or using preprocessor commands like I've demonstrated.
Next, the length of a char array in C is the number of chars it can hold. However, since each of your terms is 3 characters long plus the null character at the end you need the array to be 4 times longer than the number of terms. You can use two See the code below for how to declare this.
Finally, you need to #include the string.h header file in order to be able to work with strings in 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;
}
A char is one character. Which would be in single quotes not double quotes. "[ ]" is three character. [, the space and ] are together three characters. Each index in a char array can only hold one character at a time, so the [ or the space or the ] or some other character.