0

I am programing in C and tried to create a dynamic array using malloc.

This is the relevant code :

int K_value(int N,int M,int K)
{
    int Input,Temp_Result = 0,Result = 0;
    int i,j,r = 0;
    int* Main_Array = (int*) malloc(N * sizeof(int));
    int* Sub_Array = (int*) malloc(M * sizeof(int));        

    for (i=0; i<N ;i++) // Enter Values Into the Main array
    {
        scanf("%d",&Input);
        Main_Array[i] = Input;
    } //End of For loop

When I run in debug mode I see that Main_Array has only 1 slot and that N = 5. I was expecting Main_Array to have 5 slots.

What am I doing wrong?

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
Hacmon
  • 1
  • 1
  • 1
  • 2
    Side note, [you should not be casting the result of malloc](https://stackoverflow.com/q/605845/9614249) – Increasingly Idiotic May 15 '18 at 16:52
  • Also what program are you using to debug? – Increasingly Idiotic May 15 '18 at 16:53
  • It is impossible that Main_Array has only one slot when N == 5. You malloc (N * sizeof(int)), so it must have 5 slots when N == 5. Your error lies elsewhere. (And I agree with the above that you shouldn't cast malloc()'s results. Casts are not your friend--they hide bugs from you; only use them where absolutely necessary). – One Guy Hacking May 15 '18 at 16:55
  • when you say cast my result u mean this : int* Main_Array ? – Hacmon May 15 '18 at 17:05
  • They mean `int* Main_Array = malloc(...)` with no `(int*)` in the middle. That part is "casting". – tadman May 15 '18 at 17:13
  • 1
    Remember, something returned by `malloc` is *not* an array, but it is enough memory that it *could* hold an array of a particular size. In C pointers and arrays are often interchangeable, `*c` and `c[0]` tend to work the same, but that's not to say pointers *are* arrays, or arrays are pointers. An array can have a length, a pointer does not. – tadman May 15 '18 at 17:15
  • 1
    Additionally, can you provide us the debug information as printed on the terminal? – Ṃųỻịgǻňạcểơửṩ May 15 '18 at 17:40
  • when im cutting off the casting ive got an error said : 1 IntelliSense: a value of type "void *" cannot be used to initialize an entity of type "int *" but it still passes the compiler.. – Hacmon May 15 '18 at 22:14
  • @Hacmon Do you get the same error when you actually compile, or is it only shown by intellsense. (Intellisense uses different logic to the actual compiler) – M.M May 15 '18 at 22:30

1 Answers1

-1

You are not doing anything wrong.

Your debugger doesn't know the size of the array Main_Array. You can try casting it in the debugger to see the rest of the data.

For example, Eclipse IDE will allow you to choose "Cast to Type" or "Display As Array".

Please see this answer for Visual Studio

How to display a dynamically allocated array in the Visual Studio debugger?

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
iamJP
  • 386
  • 1
  • 12