2

I used this code to insert values for array data, but when I tried inserting the values 8 1 2 3 4 5 6 7 8(the first number 8 is the size of the array), the output was 00000000 instead of the input values 1 2 3 4 5 6 7 8. Any idea how I can make the program work?

#include<stdio.h>
#include<stdlib.h>

int main()
{
  int n,i,*data;

  scanf("%d", &n);

  data=(int *)malloc(sizeof(int)*n);//data[size]

  for(i=0;i<n;i++)
  {
     scanf("%d", &data[i]);
  }

  for(i=0;i<=n;i++)
     printf("%d",data[n]);
  printf("\n");

  return 0;
}
LPs
  • 16,045
  • 8
  • 30
  • 61
M.H.F
  • 81
  • 2
  • 5

2 Answers2

2

You need to change this part :

for(i=0;i<=n;i++)
    printf("%d",data[n]);
    printf("\n");
    return 0;
}

to :

for(i = 0; i < n; i++)
    printf("%d",data[i]);
    printf("\n");
    return 0;
}

What you do now is iterating but not using the variable i as index. Instead, you constantly try to print only data[n]. This is accessing index out of bounds as in , an array's indexes start from 0 and reach n-1, where n is the array's size. This can cause [tag: undefined-behavior] of your program.

So your for loop will either have to be :

for(i = 0; i < n; i++)

or :

for(i = 0; i <= n-1; i++)

Also, take a look on this link on why you should not cast the result of malloc. Moreover, make sure that you always check the result of malloc, like this :

data=malloc(sizeof(int)*n);
if (data == NULL)
    printf("Error in dynamically allocating memory.\n");
Community
  • 1
  • 1
Marievi
  • 4,951
  • 1
  • 16
  • 33
2
  1. The print loop should use i as index and not n as yours
  2. The loop have to go up to n-1, so correct condition have to be i<n. Your code access the "array" out of bounds which invokes Undefined Behavior
  3. You always have to check function return values.
  4. Side note: with you shouldn't cast malloc return.

Code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    size_t n,i;
    int *data;

    printf("Insert number of items: ");
    scanf("%zu", &n);

    data=malloc(sizeof(int)*n);

    if (data != NULL)
    {
        for(i=0;i<n;i++)
        {
            printf("Insert value for item %zu: ", i+1);
            scanf("%d", &data[i]);
        }

        printf("You inserted: ");

        for(i=0;i<n;i++)
            printf("%d ",data[i]);
    }
    else
    {
        fprintf(stderr, "Failed allocating memory\n");
    }

    printf("\n");

    return 0;
}
Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61