Hi all,
I would like to help me with a program in C.

I would like to make a function that saves 10 float numbers from an user.
But I would like to to do this with pointers.

My function is called float *save_array(int N)
and then I have to find the maximum value of the array with void maximum(float *Array,int N)

Any help ??

Thanks

>>Any help ??

Yes, lots of it. But you first have to post the code you have tried.

float *save_array(int N)
{
float *a;
int counter=0;

printf("Please type 10 float numbers :\n");
for(counter=0;counter<11;counter++)
{  scanf("%f",&a);}

return &a;
}

void maximum(float *Array,int N)
{
     int i=0;
    max=*Array;

for(i=0;i<N;i++)
{
   if (*(Array+i)>max)
      max=*(Array+i);
}

}

this code is a mess.

first off, you would need to change the line scanf("%f",&a); to scanf("%f",&a[i]); if you wanted to have any hope of collecting the input into the array.

but you cant just declare a float pointer like you're doing, within the 'save_array' function, and expect memory to be automagically allocated for the array

also notice, you are passing the int 'N' as a number of elements, yet you're not using that value within the function and are instead hard-coding 10 elements. make up your mind and do it one way or the other.

another problem in your 'maximum' function, is that you're passing the variable as a pointer, yet you're also trying to declare it locally. you can't do that. you have to choose one or the other. in this case, you need to pass it, because you want to analyse the values of an existing array, and not create a new one.

figure out what i'm talking about and try to fix your code accordingly.


.

Here is correction

float *save_array(int N)
{
    float *a;
    int counter=0;
    a = malloc(N * sizeof(*a)); // allocate memory for the array
    printf("Please type 10 float numbers :\n");
    for(counter = 0;counter < N;counter++)
   { 
         scanf("%f",&a[counter]);
    }
    return a; 
}

Based on jephthah comments I tried to write code:

float *save_array(int N) {
    float *a,*b;
    int i;
    // Allocate memory for N floats
    a = malloc(sizeof(float) * N);
    // Assign temp pointer 'b' to a
    b = a;
    // Get 10 floats
    for(i = 0; i < N; i++ ) 
    {
          scanf("%f", b++/*Increment pointer to next memory location*/);
    }
    printf("\nArray: ");
    // Print the array
    for(i = 0; i < N; i++ ) 
    {
          printf("%f\n", a[i]);      
    }
    return a;
}

Now your task is write maximum() function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.