简体   繁体   English

将结构传递给 C 中的函数

[英]Passing structures to functions in C

Define a struct named Book .定义一个名为Book的结构体。 Each book should have a name with exactly 3 letters (abbreviation).每本书都应该有一个名称,其中包含 3 个字母(缩写)。 Each book should also have a page count (integer), and a price (integer).每本书还应该有页数(整数)和价格(整数)。

Write a program which reads an integer n first, then reads the names , page counts and prices of n books.编写一个程序,先读取一个整数n ,然后读取n本书的namespage countsprices

Write a function which takes an array of books, and sorts them according to their prices.编写一个函数,它接受一系列书籍,并根据它们的价格对它们进行排序。 Using that function, your program should print the names and page counts of each book with the order of their prices.使用该函数,您的程序应该按照价格顺序打印每本书的名称和页数。

My Question我的问题

Can someone explain to me how to pass a structure into a function and get this code to work?有人可以向我解释如何将结构传递给函数并使此代码起作用吗? Or how they would go tackle this question.或者他们将如何解决这个问题。

struct Book{
char name[3];
int pagec;
int price;
};


void price(int size, struct Book books[size]){
int i,j, tmp;
for(i=0; i<size; i++){
    for(j=0; j<size-1; j++){
        if(books[j].price < books[j+1].price){
            books[j].price = tmp;
            books[j].price = books.price[j+1];
            books.price[j+1] = tmp;
         }
      }
   }
}

int main(void) {
int n;
scanf("%d", &n);
struct Book books[n];
int i,j;
for(i=0; i<n; i++){
    for(j=0; i<1; j++){
    scanf("%c", &books[i].name);
    scanf("%d", &books[i].pagec);
    scanf("%d", &books[i].price);
    }
   }

price(n, books[n]);
for(i=0; i<n; i++){
    printf("%c: %d - %d",books[i].name, books[i].pagec, books[i].price);
}

So you have your struct所以你有你的结构

struct Book{
   char name[10];
   int pagec;
   int price;
};

You can pass it in by passing in a pointer to it using the "address of" operator您可以通过使用“address of”运算符传递指向它的指针来传递它

void receivingFunction(Book* myBook)
{
   printf("%s", myBook->name);
}

void sendingFunction()
{
   Book myBook;
   //set values in myBook
   receivingFunction(&myBook);
}

Notice that when you are working with the pointer to book, you access members using the -> operator, not the .请注意,当您使用指向 book 的指针时,您使用->运算符访问成员,而不是. operator.运营商。

Now that example above is just for passing in a single instance.现在上面的示例仅用于传入单个实例。 What if you want to pass in an array?如果你想传入一个数组怎么办? It'll look something like this.它看起来像这样。

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

struct Book{
   char name[4]; //other answers explain well why I changed this to 4
   int pagec;
   int price;
};

void BookSorter(struct Book books[10], int booksLength)
{
    int i;
    for(i = 0; i < booksLength; i++)
    {
       printf("%s %d %d\n",  books[i].name, books[i].pagec, books[i].price);
    }
}

int main(void)
{
  Book books[10];
  //define your values for books here
  //mine are junk values since this is just an example
  for(int i = 0; i < 10; i++)
  {
      strncpy(books[i].name, "aaa", 4);
      books[i].pagec = 4;
      books[i].price = 10;
  }
  //
  BookSorter(books, 10);
}

From here you can modify your bubble sort to iterate through your array instances and swap them.从这里您可以修改冒泡排序以遍历数组实例并交换它们。 I'm not going to include that part because 1) it is beyond the scope of your original question about passing structs and 2) it really looks like you're doing homework and I don't want to give you all of it.我不打算包括那部分,因为 1) 它超出了你关于传递结构的原始问题的范围,2) 看起来你真的在做作业,我不想给你全部。 The comments below your question address ways to fix your bubble sort, one I haven't seen yet is that you're just swapping the prices of the books, not the books themselves.您的问题下方的评论解决了解决冒泡排序的方法,我还没有看到的是,您只是在交换书籍的价格,而不是书籍本身。 Your temp variable should be a struct Book , not an int .您的临时变量应该是struct Book ,而不是int Your swapping just swaps the prices of the books, which will lead to them being assigned to the wrong book for the final printing out of the answer, with the books and page counts being left in the same order they were read in. It looks like you used this example code (or maybe one of a million like it), but here it is if you need a reference for implementing bubble sort .您的交换只是交换了书籍的价格,这将导致它们被分配到错误的书籍中以最终打印出答案,书籍和页数的顺序与它们阅读的顺序相同。看起来像您使用了这个示例代码(或者可能是一百万中的一个),但是如果您需要实现冒泡排序参考,这里是。

books[n] is one struct Book (or would be, if the array had n+1 elements). books[n]一个struct Book (或者如果数组有n+1元素的话)。

The name of the array is just books , and this is what you should pass to the function:数组的名称只是books ,这是您应该传递给函数的内容:

price(n, books);

The part of your question about how to pass a struct seems to have been well answered, let me get on the second part: how I would tackle that question.您关于如何传递struct问题的部分似乎得到了很好的回答,让我进入第二部分:我将如何解决该问题。

What the struct should be is described well, so we can write without much thinking: struct应该是什么已经描述好了,所以我们可以不用多想写:

/*
    Define a struct named: Book.
    Each book should have a name with exactly 3 letters (abbreviation).
    Each book should also have a page count (integer), 
    and a price (integer). 
*/
typedef struct book {
  // three characters plus '\0'
  char name[4];
  int pagec;
  int price;
} book_t;

(No need for a typedef you can leave that part out and use the struct directly with struct books ) (不需要typedef您可以省略该部分并直接将 struct 与struct books

They want three functions, one is main() we can use it as one of the three.他们需要三个函数,一个是main()我们可以将其用作三个函数之一。 I think getting the info, allocating the memory etc. is a good use of the main() function here.我认为获取信息、分配内存等是对main()函数的一个很好的使用。

/*
    Write a program which 

        reads an integer n first, 
        then reads the names, 
        page counts 
        and prices of n books.
*/
int main()
{
  int n, i;
  book_t **books;

  puts("How many books?");
  scanf("%d", &n);

  // we need enough memory to safe "n" structs
  // at first allocate memory for n pointers
  books = malloc(n * sizeof(book_t *));
  // at each pointer allocate enough memory for one struct books
  for (i = 0; i < n; i++) {
    books[i] = malloc(sizeof(book_t));
  }
  // red the info from stdin
  for (i = 0; i < n; i++) {
    printf("Name of book (3 letter abbrev.):");
    scanf("%3s", books[i]->name);
    printf("Number of pages:");
    scanf("%d", &books[i]->pagec);
    printf("Price of book (incl. taxes):");
    scanf("%d", &books[i]->price);
  }
  // call function to sort them
  sort_books(books, n);
  // call a function to print the sorted list
  print_books(books, n);
  // we don't need the memory anymore, so free it
  // at first free the individual structs
  for (i = 0; i < n; i++) {
    free(books[i]);
  }
  // then free the memory holding all of the pointers
  free(books);

  exit(EXIT_SUCCESS);
}

The two functions for printing and sorting are similar in argument handling打印和排序这两个函数在参数处理上是相似的

/*
    Write a function which takes an array of books,
    and sorts them according to their prices.

   Doesn't say something about output, so sort in situ
*/
void sort_books(book_t ** books, int length)
{
  // OP had bubble sort, so lets do a bubble sort. Why not?
  int i, j;
  book_t *tmp;
  for (i = 0; i < length - 1; i++) {
    for (j = 0; j < length -i - 1; j++) {
      if (books[j]->price < books[j + 1]->price) {
        tmp = books[j];
        books[j] = books[j + 1];
        books[j + 1] = tmp;
      }
    }
  }
}

Printing them all is quite straightforward打印它们非常简单

/*
   Using that function, your program should 
       print the names and page counts of each book with the order of their prices. 
*/
void print_books(book_t ** books, int length)
{
  int i;
  for (i = 0; i < length; i++) {
    printf("Name %s, pages %d, price %d\n",
       books[i]->name, books[i]->pagec, books[i]->price);
  }
}

It doesn't say anything about the exact order, I took the liberty to use a descending order (from highest to lowest).它没有说明确切的顺序,我冒昧地使用了降序(从最高到最低)。 If you want an ascending order (from lowest to highest) change the comparing in the sorting algorithm:如果您想要升序(从最低到最高),请更改排序算法中的比较:

void sort_books(book_t ** books, int length)
{
  // OP had bubble sort, so lets do a bubble sort
  int i, j;
  book_t *tmp;
  for (i = 0; i < length - 1; i++) {
    for (j = 0; j < length - i - 1; j++) {
      // if (books[j]->price < books[j + 1]->price) {
      if (books[j]->price > books[j + 1]->price) {
         tmp = books[j];
         books[j] = books[j + 1];
         books[j + 1] = tmp;
      }
    }
  }
}

Please be aware that I omitted all checks!请注意,我省略了所有检查! You need to check the returns of malloc() and scanf() , if n is an integer, if all of the other numbers are numbers and so on!您需要检查malloc()scanf()的返回,如果n是整数,如果所有其他数字都是数字等等!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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