Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a value for an array using malloc [closed]

Tags:

arrays

c

malloc

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;
}
like image 405
M.H.F Avatar asked May 13 '26 00:05

M.H.F


1 Answers

  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 c 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;
}
like image 147
LPs Avatar answered May 15 '26 13:05

LPs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!