I have to solve this problem: "Write a program that reads from the keyboard a sequence of 10 integers, and writes the same sequence in reverse order, dividing by 2 the even elements of the sequence."
I want to know the size of the array p to print it in the reverse order but when I try to get the size of array with "l = sizeof(p)/sizeof(p[0])" the for loop below doesn't works.
int main(){
int n,i;
int *p;
int l;
printf("How long the array? ");
scanf("%d",&n);
p = malloc(n*sizeof(int));
if(p != NULL){
for(i=0;i<n;i++){
printf("Insert number in index (%d) of array: ",i);
scanf("%d",p+i);
}
l = sizeof(p)/sizeof(p[0]);
for (i=n;i == 0;i--){
if(p[i] % 2 == 0){
printf("%d ",p[i]/2);
}
else{
printf("%d",p[i]);
}
}
}
else{
printf("ERROR!!");
}
return 0;
}
The return value of sizeof will be a size in bytes - not of the array, but the pointer, which is an integer in this case. What you want is the length. You have the length stored in n.
Your for-loop is a bit confusing. Try using n - 1 (the length of the array) in order to start the loop by accessing the last index value of the array. Also, the printf
inside the else block doesn't space the output correctly. Try the following code:
for (i = n - 1; i >= 0; --i)
{
if (p[i] % 2 == 0)
{
printf("%d ", p[i] / 2);
}
else
{
printf("%d ", p[i]);
}
}