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;
}
i as index and not n as yoursn-1, so correct condition have to be i<n. Your code access the "array" out of bounds which invokes Undefined BehaviorCode
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With