'Reversing the contents of an array
I am trying to reverse the contents of an array and store them in another array, but it just outputs last element of the original array. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
float* copy(const float *source, int s){
float* target;
int x=s-1;
target=(float*)malloc(s*sizeof(float));
for (int i= 0; i<s; i++){
target[x - i]=source[i];
}
return target;
}
int main(){
int nelements;
float *source= NULL;
float *target=NULL;
printf("Enter no of elements:");
scanf("%d", &nelements);
source=(float*)malloc(nelements*sizeof(float));
for (int i=0; i<nelements; i++){
scanf("%f", &source[i]);
}
target=copy(source, nelements);
printf("%f\n", *target);
free(source);
free(target);
return 0;
}
Solution 1:[1]
but it just outputs last element of the original array
Yes, that would be what the line printf("%f\n", *target); achieves. You need to print each item in target from inside a for loop.
Solution 2:[2]
You have to print your "target" like you scan your "source" to print all element of array one by one.
Solution 3:[3]
Maybe you could try to print your "target" like you scan your "source" to print all element of array one by one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lundin |
| Solution 2 | |
| Solution 3 | 02zjz |
