Home > Back-end >  How to copy the data within the pointer into a float array using memcpy()?
How to copy the data within the pointer into a float array using memcpy()?

Time:08-04

I wanted to copy what's within the amount pointer into the Fquantity[] array, but it shows me error "argument of type "float" is incompatible with parameter of type "void*"". How should I make it work? Thank you.

    char buffer[BSIZE]; 
    char d[] = "\t\n"; //delimeter
    char *fcode(0), *amount(0), *hos(0), *next; 
    char Fcode[BSIZE][100]; //store in array to do comparison
    float Fquantity[BSIZE]; //store in array to do accumulation
    float total;
    int ctr = 0, x = 1;

    fopen_s(&fptr, "Dist.txt", "r");
    while (fgets(buffer, BSIZE, fptr) != NULL) //split string in FILE and store into Fcode and Fquantity array
    {
        fcode = strtok_s(buffer, d, &next);
        printf("\ncode: %s\n", fcode);
        memcpy(Fcode[ctr], fcode, 5);

        amount = strtok_s(NULL, d, &next); 
        printf("amount: %.1f\n", atof(amount));
        memcpy(Fquantity[ctr], amount, 5); //Fquantity[ctr] shows the error
        
        hos = strtok_s(NULL, d, &next);
        printf("hospital: %s\n", hos);

        ctr  ;
    }
    fclose(fptr);

CodePudding user response:

To use memcpy function, you have to give it the pointers of both buffers, But in memcpy(Fquantity[ctr], amount, 5) you gave it Fquantity[ctr] which is a value of a variable not address of it. To give it the address of Fquantity[ctr] just add and & before its name. So the answer is memcpy(&Fquantity[ctr], amount, 5).

CodePudding user response:

memcpy is not the right tool for your purpose: you must convert the textual representation of the numbers in the internal binary float format. You can use strtod() or scanf() for this.

Note that char *fcode(0), *amount(0), *hos(0) makes no sense in C.

Your system probably coerces you to use the so called safer string functions such as fopen_s and strtok_s, but it is useless to call fopen_s or strtok_s and not test their return values.

Here is a modified version using standard functions.

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

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

int read_data(void) {
    char buffer[256]; 
    char delimiters[] = "\t\n";
    char Fcode[BSIZE][100]; //store in array to do comparison
    float Fquantity[BSIZE]; //store in array to do accumulation
    char hos[100];
    int ctr = 0;

    if ((fptr = fopen("Dist.txt", "r")) == NULL) {
        fprintf(stderr, "cannot open Dist.txt: %s\n", strerror(errno));
        return -1;
    }
    while (fgets(buffer, sizeof buffer, fptr) != NULL) {
        //split string in FILE and store into Fcode and Fquantity
        if (sscanf(buffer, "           
  • Related