0

I've established two string arrays and I want to put them together. Here are my code:

#include <stdio.h>
#include <string.h>
int main(void)
{
   const char brown[10] = {'B','r','o','w','n'};
   printf("color: %s\n",brown);
   const char yellow[10] = {'Y','e','l','l','o','w'};
   printf("color: %s\n",yellow);

 char a=brown,b=yellow;

 printf("color: %c %c\n",a,b);
 return 0;

For further usage, I need to use "if" to determine their orders. I want the output to be like "color: Brown Yello", but I does not find a way to assign string arrays in C. It is not like int and double type. How can I assign string to a new variable? (in this case is char a and b) Thanks in advance!

6
  • 1
    You can't assign a whole string to one char. Also, those strings aren't correctly null-terminated. Just put const char brown[] = "Brown"; instead. Commented Jan 29, 2020 at 7:41
  • this looks like homework. please read asking about homework and edit your question if required. Commented Jan 29, 2020 at 7:53
  • printf("color: %s %s\n",a,b); will print the strings instead of single characters. Commented Jan 29, 2020 at 7:55
  • 2
    @Blaze Strings are null-terminated, as arrays are longer than initialiser list. Remaining elements are filled with zero values... Still your proposition is better ;) Commented Jan 29, 2020 at 8:50
  • @Aconcagua I completely forgot about that. Thanks for reminding me. Commented Jan 29, 2020 at 8:53

4 Answers 4

2

You're missing the terminating NUL.

const char yellow[] = {'Y','e','l','l','o','w',0};

That said, it's simpler to use the following equivalent syntax:

const char yellow[] = "Yellow";  // NUL added automatically.

Since it's constant, you don't need to create a local array.

const char *yellow = "Yellow";

The next problem is that you try to assign the array to a char, which makes no sense. You could make a copy of the array, but copying the pointer is sufficient.

const char *a = brown;
const char *b = yellow;

Finally, you want to use %s to print a string.

printf("%s %s\n", a, b);

All together,

const char *yellow = "Yellow";
const char *brown  = "Brown";

const char *a = brown;
const char *b = yellow;

printf("%s %s\n", a, b);

or just

const char *yellow = "Yellow";
const char *brown  = "Brown";

printf("%s %s\n", yellow, brown);
Sign up to request clarification or add additional context in comments.

2 Comments

In original question there's a length specifier longer than initialiser list, so there will be a terminating null...
Ah, didn't realize that unassigned elements would get initialized. Still, hardcoding some arbitrary length is not the easy to go.
0

want the output to be like "color: Brown Yellow",

If you are not modifying the strings, and that is a reasonable assumption given the const char you can use the code as below

const char brown[10] = "Brown";
const char yellow[10] = "Yellow";

printf("color: %s %s\n",brown,yellow);
```

1 Comment

Thanks for your response! Since I have 12 colors to combine, Is there a way not to set constant?
0

It's easier to initialize strings using string literal like this

const char your_string[] = "This is string.";

To concatenate two strings you will need char *strcat(char *dest, const char *src) from string.h. Be aware that you will need to ensure that your dest array contains enough space for both strings.

#include <string.h>

int main () {
   char str[] = " world";
   char dest[32]; // we need larger array to hold the result

   strcpy(dest, "hello"); // copy string hello to dest

   strcat(dest, src); // dest now contains "hello world"

   return(0);
}

1 Comment

Hi, thanks for your answer. Can this method apply to a multiple-assigning code? Since I have 12 colors, and I need to arrange them to 4-color combination based on "if statement".
0

I know this has been answered, but to address one of the questions you asked in comments:

"...Can this method apply to a multiple-assigning code? Since I have 12 colors, and I need to arrange them to 4-color combination based on "if statement"...

I wanted to suggest an approach that has not yet been discussed.

If you know that you have 12 colors that need to be selected via logic in your code, you can use the following components to a simple executable to do what you are asking:

  • a single array of strings variable that contains 12 color strings,

  • an accompanying enum providing a human readable index to access colors in the array.

  • a variadic function designed print a list of any number of any combination of color selections.

The following complete code example provides a simple illustration of using these 3 items in conjunction: (The code can be modified to accommodate using if/then/else or switch() statement selection criteria as needed.)

enum {
    RED,
    ORANGE,
    YELLOW,
    GREEN,
    BLUE,
    PURPLE,
    BROWN,
    MAGENTA,
    TAN,
    CYAN,
    OLIVE,
    MAROON,
    MAX_COLOR
};

//constant character array of colors    
const char color[MAX_COLOR][10] = {"Red","Orange","Yellow","Green","Blue","Purple","Brown","Magenta","Tan","Cyan","Olive","Maroon"}; 
//prototype
void print_color( int nHowMany, ... );

int main(void)
{
   //your selection criteria code can precede this call to a variadic fucntion
   //from which you can call any number of any combination of the enumerated
   //values in the enum... 

    //argument 1 is number of colors, then enter colors to be printed 
    print_color(3, MAGENTA, OLIVE, YELLOW);

    //However, if for your own reasons you still want to use discrete 
    //pointer variables, the string array can be used to initiate 
    //them as well:
    const char *a = color[RED];
    const char *b = color[ORANGE];
    const char *c = color[YELLOW];
    // ...
    const char *l = color[MAROON]

    return 0;
}


void print_color( int nHowMany, ... )
{
    int  color_index =0;

    va_list intArgumentPointer;
    va_start( intArgumentPointer, nHowMany );
    printf("%d Colors Selected:\n", nHowMany);
    for( int i = 0; i < nHowMany; i++ )
    {
        color_index = va_arg( intArgumentPointer, int );

        printf("%d %s\n", i+1, color[color_index]) ;
    }
    va_end( intArgumentPointer );

} 

The output from the above example:
enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.