Home > OS >  Most Basic 1D Array in C not working as expected
Most Basic 1D Array in C not working as expected

Time:11-29

I am very new to C and I am just learning about arrays. This has to be probably the worst question but I can't understand what am I doing wrong here:

I have a basic array that will store 10 items. When I assign values one by one I get a strange error. I can't see what could possibly be wrong here. I have seen so many tutorials & I can't see myself doing anything different:

#include<stdio.h>
//The Boolean lib needs to be included
#include<stdbool.h>
/**
 * @file DataTypes.c
 
 * 
 * Learning Data Types
 */

/**
 * Primitive Data Types:
 * char, int, double, float, boolan?
 */

/**
 * Integers 
 * These could be signed or unsigned.
 * The different types of Integers are: 
 * short, int & long. 
 * Difference mainly to do with memory, can learn more as I go
 */

//Basic Signed int
int number = 727;

/**
 * The reason for this is because default is signed. So it could be either, so this is easy.
 * This means we only need to say unsigned int when we know form sure we will not put a negative value
 * 
 */
int unsignedIntDidntThrowError = -33;

/**
 * Explicit unsigned int.
 * Use when we are sure there wont be a negative number
 */
unsigned int unsignedInt = 46;


/**
 * This should throw an error because its unsigned and we gave negative value?
 * Didn't throw an error. I expect this to be just a memory issue ?
 */
unsigned int unsignedIntShouldThrowError = -33;

/**
 * @brief Short VS Long vs medium ?
 * Just a brief about the difference, if its just memory I can leave
 * There is no medium, only short & long
 */
short shortInt = 33;

long longInt = 45;

/**
 * @brief Doubles & floats
 * Doubles are more precise than floats
 * 
 */
double myFirstDouble = 636.78f;

/**
 * Doubles & Floats
 * Doubles & floats dont have signed / unsigned but double has a long double
 */

//Can we keep a double without trailing f? Yes!
double canIKeepDoubleVarWithoutTrailingF = 76.66;

//Float worked perfect too
float myFirstFloat = 36.78f;

/**
 * Boolean?
 * Lets see if boolean exists:
 * Need to get the stdbool.h file, Now I realise how primitive C is, 
 * I could always just use 1 & 0
 */
bool boolTrueEg = true;


bool boolFalseEg = false;


/**
 * Char:
 * In C, is quiet primitive, strings will be done through arrays next
 * 
 */
char charEg = 'M';

/**
 * This threw an error, probably because it is more than 1 char
 * 
 */
//unsigned char unsignedCharEg = '-a'; //Throws error
unsigned char unsignedCharEg = '-'; //Works

/**
 * Test Arrays:
 * Perfect Basic Arrays works with char, no lib needed for this
 */
char mother[] = "Mama";

/**
 * Int array example:
 * Unfortunately it takes curly braces which is odd, would have prefered if it was square
 */
int intArrayEg[] = {3, 6, 9};

/**
 * Another int array which is initialised first so I can put the number of chars it will take
 * In this example, the array can take 5 values. We test each below
 * Throwing an error so we are leaving it for now
 */
int tenItemArray[10];
// tenItemArray[0] = 1;






/**
 * @param argc 
 * @param argv 
 * @return int 
 */
int main(int argc, char const *argv[])
{
    /* code */
    // printf("\nMy First Integer, var & included file with int var: %d", number);
    // printf("\nMy First function: %d", getArea(9, 9));
    // printf("\nResult: %f", myFirstDouble);
    // printf("\nFloats work same way? %f", myFirstFloat);
    // printf("\nAbstract Result: %f", canIKeepDoubleVarWithoutTrailingF);
    // printf("\nShort Int is still be digit?: %d", shortInt);
    // printf("\nLong Int is still be digit?: %d", shortInt);

    // printf("My first Boolean, True & False: %d, %d", boolTrueEg, boolFalseEg);
    // printf("Char example: %c", charEg);
    // printf("Unsigned Char example: %c", unsignedCharEg);

    //printf("My first char from array: %c", mother[0]);

    //printf("Int Array example: %d", intArrayEg[2]);
    printf("Ten Item array: %d", tenItemArray[0]);//Throws error

    return 0;
}

Errors:

 PrimitiveTypes.c:118:2: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
 tenItemArray[0] = 1;
 ^
PrimitiveTypes.c:118:2: error: redefinition of 'tenItemArray' with a different type: 'int [0]' vs 'int [10]'
PrimitiveTypes.c:117:5: note: previous definition is here
int tenItemArray[10];
    ^
1 warning and 1 error generated.

I can't seem to understand the errors. How can type specifiers be missing when I just declared the array with int value? How have I redefined the array? I am just adding a value one by one

CodePudding user response:

You may not place statements in the file scope as you have done.

int tenItemArray[10];
tenItemArray[0] = 1;  // <== this is a statement

Instead you could just declare the array with an initializer the following way

int tenItemArray[10] = { 1 };

or

int tenItemArray[10] = { [0] = 1 };

CodePudding user response:

The reason this is broken is because the code outside of main() is a series of declarations and is evaluated at compile time while the code in main() is executed at run time.

A statement like

tenItemArray[0] = 1;

doesn't make sense outside of the main function because it is an action (statement) rather than a declaration.

My c is a bit rusty but something like this might allow you to initialize those values at compile time.

int tenItemArray[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};

The compiler error is a bit cryptic but here is how it sees your code:

int tenItemArray[10];
// Ok, I will create tenItemArray[10] for you.

tenItemArray[0] = 1;
// Wait, this doesn't have a type. I will assume it's an int.
// Wait, you already make something called: int tenItemArray[10]
//   and now you are trying to make something called: int tenItemArray[0]
// I give up.

CodePudding user response:

I guess that you have something like this:

int tenItemArray[10];
tenItemArray[0] = 1;


int main() {

    return 0;
}

Then this should not work. Move tenItemArray[0] = 1 inside function main.

  • Related