Home > Back-end >  How can I increment the value in the called function?
How can I increment the value in the called function?

Time:07-21

How can I pass the pointer to the structure to another function?

sample:

#include<stdio.h>

    
struct customer{
char name[50];
int number;
};

void input(){

struct customer details;
   
   printf("enter your name:  ");
   scanf("%s",details.name);
   
   details.number  ;
   printf("%d\t%s",details.number,details.name);
}
int main(){
    struct customer details;
    
    input();
    
    //pcust->number  ; how should I declare this?
    
    printf("%d\t%s",details.number,details.name);
    
}

how do you automatically assign a number in a struct where I can call its value in other functions?

suppose I have this struct

struct customer{
char name[50];
int number;
};

and request input for the user

void input(){

struct customer details;

   printf("enter your name");
   scanf("%s",details.name);

   printf("enter your number");
   scanf("%d",&details.number);
}

instead of asking them to enter their number in the function to call it by value, how can I assign it automatically, so I can call it by its value? The possible output I need is like this so that in the next function again, I can call by its value again.

1 customer1
2 customer2
....

CodePudding user response:

  1. Your main problem is that you do not use any function parameters.
  2. You need to have some kind of search (for example if you want to modify a customer record
  3. Use arrays to store multiple data.

Example:

struct customer
{
    char name[50];
    int somedata;
};

struct database
{
    size_t size;
    struct customer customers[];
};

struct customer *findCustomer(const struct database *db, const char *name)
{
    struct customer *result = NULL;
    if(db)
    {
        for(size_t i = 0; i < db -> size; i  )
            if(!strcmp(db -> customers[i].name, name))
            {
                result = (struct customer *)&db -> customers[i];
                break;
            }
    }
    return result;
}

struct database *addCustomer(struct database *db, const char *name)
{
    size_t newSize = db ? db -> size   1 : 1;

    db = realloc(db, newSize * sizeof(db -> customers[0])   sizeof(*db));
    if(db)
    {
        strcpy(db -> customers[db -> size].name, name);
    }
    return db;
}

CodePudding user response:

#include <stdio.h>

struct customer
{
    char name[50];
    int number;
};

void input(struct customer *pDetails)
{

    printf("enter your name:  ");
    scanf("%s", pDetails->name);

    pDetails->number  ;
    printf("%d\t%s \n", pDetails->number, pDetails->name);
}

int main()
{
    struct customer details = {};

    input(&details);

    printf("%d\t%s \n", details.number, details.name);
}
  •  Tags:  
  • c
  • Related