Why array variable doesn't work inside the IF statement of C?

Debojit Acharjee 455 Reputation points
2023-05-24T11:22:54.03+00:00

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:

#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;
}

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.

Developer technologies .NET .NET Runtime
Developer technologies Visual Studio Debugging
Developer technologies C++
Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

Accepted answer
  1. Giovanni Dicanio 160 Reputation points
    2023-05-24T18:29:33.18+00:00
    char NumberType[] = "POSITIVE";
    ...
    
    if (Number <0)
    {
        NumberType[10] = "NEGATIVE";
    }
    

    In C, the proper way to write a string into a destination char[] buffer is to use a function like strcpy. For example:

    // Instead of NumberType[10] = "NEGATIVE" use:
    strcpy(NumberType, "NEGATIVE");
    

    Even better, Microsoft implemented a series of safer functions to operate with strings in C, for example, the "safer" equivalent of strcpy is strcpy_s. Basically, when you use these safer functions, you pass an additional parameter that specifies the size of the destination buffer. In this way, the strcpy_s function is able to prevent buffer overflows (i.e. writing data outside proper buffer boundaries), which are a source of dire bugs and security problems.

    The above code can be rewritten using the safer strcpy_s like this:

    // A safer version of the previous strcpy call.
    // Note the additional _countof(NumberType) 
    // to specify the size of the destination buffer.
    strcpy_s(NumberType, _countof(NumberType), "NEGATIVE");
    

    If you can use C++ instead of pure C, you can enjoy writing even safer and simpler code, for example using the std::string class, and its overloaded operator= for copying strings. For example:

    #include <string> // for std::string
    ...
    
    std::string numberType = "POSITIVE";
    ...
    if (...) {
        numberType = "NEGATIVE";
    }
    
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Guido Franzke 2,191 Reputation points
    2023-05-24T12:29:00.1833333+00:00

    Hello,

    there are 2 mistakes in your code:

    1. You cannot assign an already defined char array with operator = . Use strcpy(NumberType, "NEGATIVE");
    2. NumberType has constant length 9. With NumberType[1] you get the single char 'E'. NumberType[10] will be out of range.

    Define your variable with "char NumberType[10];" and assign values with strcpy.

    Regards, Guido

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-05-24T15:33:47.3633333+00:00

    in C, the char data type is a one byte signed integer numeric (-128 - 127). the int data is a signed numeric the same size as an address.

    in C a string literal like "test", is a null terminated array of char. so your line:

    char NumberType[] = "POSITIVE";
    

    assigns the address of the string literal to the variable NumberType. your NumberType[10], refers to the address of the Literal + 10. this is outside the address range of the literal, so setting it to a value will overlay some other value. this know as buffer overrun and causes memory corruption.

    the line

    NumberType[10] = "NEGATIVE";
    

    set the NumberType address + 10 to the address of the "NEGATIVE" literal, but the address will be shorted to 8 bits. (again this is a buffer overrun and corrupts memory).

    the code could be written with pointers and may be clearer:

     char* POSITIVE = "POSITIVE";     // pointer to literal
     char* NEGATIVE = "NEGATIVE";     // pointer to literal
     char* NumberType = POSITIVE;     // copy address value
     *(NumberType + 10) = NEGATIVE;   // update offset 10 to literal address
    

    in c the array is just shorthand for address calculation.

     int buff[] = {0,0,0,0);        // define buff as address of literal array
     buff[2] = 1;                   // use [] (generates below code)
     *(buff + sizeof(int) * 2) = 1; // use address arithmetic
    

  3. Debojit Acharjee 455 Reputation points
    2023-05-26T06:20:41.75+00:00
    #include<stdio.h>
    
    int a, i, array_size;
    
    int main ()
    {
        char num[] = "POSITIVE";
    
        printf("Enter a number: ");
        scanf("%d", &a);
    
        if (a <0)
        {
            char num[] = "NEGATIVE";
        }
    
        printf ("The number is : ");
    
        array_size = sizeof (num);
    
        for (i = 0; i < array_size; i++)
        {
            printf ("%c", num[i]);
        }
    
        return 0;
    }
    This program shows the array characters only when the number is POSITIVE, but never shows when it's NEGATIVE. Why the array initialized inside the array is not displayed? Is array never initialized inside if-statement.
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.