1

I am doing an assignment for class and I thought I would bug you all with a question:

So the purpose of the program is for the user to enter the size of the array and then initialize it with some data. Max size is 20. My issue is that the array crashes when the sets the size beyond 14 and tries to initialize it. So forexample, if it sets the size as 20, it accepts it, but when I try to initialize it, it crashes. I have no idea what I am doing. your help is much appreciated.

Thank you very much,

Essi

int main ()
{

     int sizeOfArray = 0; //size Of Array
     float myArray[sizeOfArray];

     //I have a piece a line or two of code that asks the user for the size of the    
       array

     printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
     do
     {
           printf("Enter array element %d : ", initCounter+1);
           myArray[initCounter] = userInitArray();
           initCounter++;
      }while (initCounter < sizeOfArray);
}

float userInitArray()
{
      float num;
      scanf("%f", &num);
      return num;
}
4
  • where is initCounter initialized ? Commented Nov 18, 2013 at 20:47
  • If this is C code, why did you also tag it [c++]? Commented Nov 18, 2013 at 20:48
  • 3
    You may as well stop right after the second line in main(). Literally, nothing good can follow that. Commented Nov 18, 2013 at 20:48
  • @Raxvan, hopefully in static storage duration somewhere, otherwise OP is in for a world of pain :-) Commented Nov 18, 2013 at 21:46

7 Answers 7

3

These two lines

 int sizeOfArray = 0; //size Of Array
 float myArray[sizeOfArray];

Create an empty array. So whatever you try to store in this array later on is access out of bounds and invokes undefined behavior. The fact that your program crashes on 14th call is simply luck. It could have crashed on the first one just as well.

Sign up to request clarification or add additional context in comments.

Comments

2
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];

Your array is created here with a size of zero. It doesn't magically expand when you later increase sizeOfArray. You need to get the size variable set first (from your 'line or two of code' user input) then create the array based on that.

You may also want to impose some sensible upper limit on your array size so you don't blow up your stack when trying, for example, to create a one-billion-entry array :-)

Comments

1

You have a (variable-length) array of size zero. You need to first ask for the size, and then allocate the array. Otherwise any attempts to assign to array elements would result in undefined behaviour.

Comments

1

You could do :

int sizeOfArray; //size Of Array
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
float myArray[sizeOfArray]; // not a good practice 

The right way to do it would be:

int sizeOfArray; //size Of Array
float *myArray;
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
myArray=malloc(sizeof(float)*sizeOfArray); 

You may use the pointer as a common array then. and call like this: myArray[3] = doSomething();

EDIT Note that since you already know the max size you could avoid doing dynamic allocations listed above:

#Define MAXSIZE 20
int main ()
{

     int sizeOfArray; //size Of Array
     float myArray[MAXSIZE];

     printf("tell me the size of the array\n");
     scanf("%d",&sizeOfArray);

     printf("\nLet's Initialize an array of size %d!!\n", sizeOfArray);
     do
     {
           printf("Enter the element at myArray[%d] : ", initCounter+1);
           myArray[initCounter] = userInitArray();
           initCounter++;
      }while (initCounter < sizeOfArray);
}

float userInitArray()
{
      float num;
      scanf("%f", &num);
      return num;
}

Probably this last option is what your teacher is actually looking for.

1 Comment

Thank you for your help and input! WORKED!! Much appreciate it!!
0

You need to read sizeOfArray before you allocate myArray dynamically like this:

float * myArray = malloc(sizeOfArray * sizeof(float));

This is allocating sizeof(float) * sizeOfArray bytes of memory on heap and assigning address of allocated memory to myArray.

This is maybe hard to understand about arrays in C, they are really just pointers into memory - in your program the array myArray is allocated statically on stack and is of size 0. You cannot add any elements to it or assign to any index, it will not grow, its forewer 0 float elements long. Best thing that can happen to your program in this case is that it will crash. Worst case, it will not crash and strange things will happen;

You really should read something about memory allocation/management in C.

3 Comments

Thank you for your help and input! Greatly appreciate it!
You don't need dynamic memory allocation here, C has had VLAs for ages. Even if you do go the malloc way, it's bad form to cast the return value. And arrays are not pointers. They often decay into a pointer to the first element, but there are very clear differences.
Thanks @paxdiablo, you are right about the cast. I did forget about VLAs , doing more C++ last 20 years :) I stand corrected. You are right about the arrays are not pointers thing, but trust me, I understand the difference, but in the end, for example when passing it as function argument, it's just pointer.
0

I think you forget to add function prototype in the beginning of your program (before main).
And also

 int sizeOfArray = 0; //size Of Array
 float myArray[sizeOfArray];   

is wrong.
As you are using variable length array (valid in C99), you can do it as

 int sizeOfArray; //size Of Array
 printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
 float myArray[sizeOfArray];

3 Comments

this is illegal in C. Sorry :)
@egur; This is legal in C (C99 allows this) :)
Its not really legal, but gcc does "understand" such things and handle them quite well.
0

dynamic arrays are not supported in C or C++. Change your array to:

float* myAraray;
//later when you have the size , allocate it:
myArray = (float*)malloc(arrSize * sizeof(float));

1 Comment

Dynamic arrays are supported by C99.

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.