How to pass the field of a struct to a function in a library separately?

Asked

Viewed 550 times

1

Hello, everybody.

I have a program that has a structure like this:

struct itemDeLista{ char nomeProd[10]; float quant; float vUnit; int item; };

But I need to count the number of letters in the string nameProd[10], as the teacher asked us not to use the string. h am doing strlen function in a library itself, I am getting char by scanf but when I step into the library function, there are some errors. I’ll put the whole code.

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

struct itemDeLista{
    char nomeProd[10];
    float quant;
    float vUnit;
    int item;
};

struct itemDeLista valores;

int main(){
  int k = 0;

  scanf("%[A-Z a-z]",valores.nomeProd);
  printf("%s\n", valores.nomeProd);
  k = strcnt(valores);
  printf("%d", k);
return(0);
}

This is the main program, following is the library and the function to count the number of characters.

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

int strcnt(struct itemDeLista m);

int strcnt(struct itemDeLista m){
   int i = 0, cont = 0;
   while(1){
      if(m.nomeProd[i] != '\0'){
      cont++;
      }
    else{
        break;
    }
    i++;
  }
return(cont);
}

I really appreciate your help, thanks!

1 answer

1


With the definition of struct in the main program the library has no information about it.

You have to put the definition of struct itemDeLista in a file that both "sources" have access to; for example: itemDeList. h

// itemDeLista.h
#ifndef ITEMDELISTA_H
#define ITEMDELISTA_H
struct itemDeLista {
    char nomeProd[10];
    float quant;
    float vUnit;
    int item;
};
#endif

Then include this header in your programs

#include <stdio.h>
#include <stdlib.h>
#include "biblio.h"
#include "itemDeLista.h"

struct itemDeLista valores;

int main(void) {
    int k = 0;

    scanf("%9[A-Z a-z]", valores.nomeProd);
    printf("%s\n", valores.nomeProd);
    k = strcnt(valores);
    printf("%d\n", k);
    return(0);
}

and at the source of your library

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

int strcnt(struct itemDeLista m);

int strcnt(struct itemDeLista m) {
    int i = 0, cont = 0;
    while (1) {
        if (m.nomeProd[i] != '\0') {
            cont++;
        } else {
            break;
        }
        i++;
    }
    return cont;
}

If the "Biblio. h" header already has the struct you have to include it in the library.

  • Thank you very much, it worked here. One question, in this shared header format for both, I can: values.Uant = 15, for example, in the two files?

  • You can, but it’s not advisable to use global variables. It is best to use a normal variable inside main and pass its address to other functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.