Click here to Skip to main content
16,016,580 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I wrote a C program using VS code, and tried to assign a string to an array inside an If-statement of C language. But it doesn't work. However, only integer variables are successfully assigned. Why is that?

Here is the code:
C
#include <stdio.h>

int main ()
{
    char NumberType[] = "POSITIVE";
    int Number;
    printf("Enter a number: ");
    scanf ("%d", &Number);
    if (Number <0)
    {
        NumberType[10] = "NEGATIVE";
    }

    if (Number == 0)
    {
        Number = 4;
    }

    Number = (Number/2);
    printf("The number divided by 2 is %d and it's a %s number", Number, NumberType);
    return 0;
}


What I have tried:

The string "NEGATIVE" can't be assigned to the array NumberType[10] when the first if-statement is entered, but the integer '4' is assigned to 'Number' variable when the second if-statement is entered.
Posted
Updated 24-May-23 2:20am
v2

Quote:
C
NumberType[10] = "NEGATIVE";
That attempts to store an array of chars in element 10 of an eight-element array of char values. That's not going to work.

c - Assigning strings to arrays of characters - Stack Overflow[^]

Apparently, you can't assign one array to another in C, so NumberType = "NEGATIVE"; won't work. You'll need to use strcpy instead.
C
strcpy(NumberType, "NEGATIVE");
 
Share this answer
 
To add to what Richard has said, this code can never work:
    char NumberType[] = "POSITIVE";
...
        NumberType[10] = "NEGATIVE";
because NumberType is an array of characters, and so is "NEGATIVE" (string literals are stored as an array of characters because C has no concept of strings). You are trying to assign nine characters (because C strings are null terminated which means they have a "hidden character" at the end which tells the system when to stop processing it) into a single character location in a character array which will not fit.

In fact it's worse than that, because the assignment would attempt to write a pointer value (because arrays are really pointers to the data they contain) and that means it would get really messed up depending on the size of a pointer in your system.

What I'd suggest is to use a flag which says if it's position or negative (an int is fine: 0 is FALSE, non-zero is TRUE in C). So I'd do this:
C
#define TRUE 1
#define FALSE 0
#define POSITIVE TRUE
#define NEGATIVE FALSE
...
int NumberType = POSITIVE;
...
if (...)
   {
   NumberType = NEGATVE;
   }
...
printf("The number divided by 2 is %d and it's a %s number", Number, NumberType ? "POSITIVE" : "NEGATIVE");
Now your code is both more readable and easier to work with.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900