Home > Net >  Reversing the contents of an array
Reversing the contents of an array

Time:05-18

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;
}

CodePudding user response:

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.

CodePudding user response:

You have to print your "target" like you scan your "source" to print all element of array one by one.

CodePudding user response:

Maybe you could try to print your "target" like you scan your "source" to print all element of array one by one.

  •  Tags:  
  • c
  • Related