简体   繁体   中英

How to take the elements of pointer array in C?

I'm trying to make a pointer array which in my case can point to three elements.I want to take the elements at run time and want to access each element but I couldn't. Here is the source code.

#include<stdio.h>

main(){
    int i;
    float *coefficient[3];
    for(i=0;i<=2;i++){
        scanf("%f",coefficient[i]);
    }
    for(i=0;i<=2;i++){
        printf("%f\n",*coefficient[i]);
    }
}

Change

float *coefficient[3];

to

 float coefficient[3];

As you need an array of float not float pointers

Then,

change

scanf("%f",coefficient[i]);

to

scanf("%f",&coefficient[i]);

As you need a pointer to the float to read in. Please also check the return value from scanf

As you have an array of floats

printf("%f\n",coefficient[i]);

is what you require

Your pointers are uninitialized, so dereferencing them causes undefined behavior. You need to allocate memory for them, eg using malloc() .

    for(i=0;i<=2;i++){
        coefficient[i] = malloc(sizeof *coefficient[i])
        scanf("%f",coefficient[i]);
    }

And after you print them, you should use free() to release the memory.

For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

You declared an array of three pointers but the elements of the array are not initialized and have indeterminate values.

As a result calling the function scanf in this loop

for(i=0;i<=2;i++){
    scanf("%f",coefficient[i]);
}

invokes undefined behavior.

The pointers which are elements of the array shall point to a valid memory where data may be stored using the pointers.

For example you can for each pointer dynamically allocate memory that will be pointed to by the corresponding pointer

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    enum { N = 3 };
    float  *coefficient[N];

    for ( size_t i = 0; i < N; i++ )
    {
        coefficient[i] = malloc( sizeof( float ) );
    }

    for ( size_t i = 0; i < N; i++ )
    {
        scanf( "%f", coefficient[i] );
    }

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%f\n", *coefficient[i] );
    }

    for ( size_t i = 0; i < N; i++ )
    {
        free( coefficient[i] );
    }

    return 0;
}

If to enter

1.1
2.2
3.3

then the output will look like

1.100000
2.200000
3.300000

You can format the output as you like.

In general you should check that a call of malloc and/or of scanf was successful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM