-1

重写这个程序,为你打印的每一种方式使用一个函数。尝试将指针传递给这些函数,以便它们处理数据。请记住,您可以声明一个函数来接受指针,但只需像使用数组一样使用它。

你好吗?我有用于循环打印索引数组和指针索引的 c 代码。这里没有功能的正确代码:

       int main(int argc, char * argv[])
       {

       int number[] = {123, 456, 789};
       char *strchars[] = {
         "ABC", "DEF", "GHI"
       };

       int count = sizeof(number) / sizeof(int);
       int i = 0;

       for(i = 0; i < count; i++) {
          printf("%s has %d \n", strchars[i], number[i]);
       }

       // with pointers

       int *po_number = number;
       char **po_strchars = strchars;

       // loop with pointiers

       for(i = 0; i < count; i++) {
           printf("%s has %d \n", *(po_strchars+i), *(po_number+i));
       }
       return 0;
    }

但我需要使用每种打印方式。但我想不通。这里我的代码有函数但没有指针和字符,只有整数。告诉我如何使它正确:

    #include <stdio.h>
    // void print_arg(int a[], int b[]);

    // now it right?

    // void print_arg(int a[], int b[])

    void print_arg(int a, int b);

    // or now it right?

    void print_arg(int a, int b)
    {
          int a;
          int b;
          int count = sizeof(a) / sizeof(int);
          int i = 0;
              //and it
          for(i = 0; i < count; i++) {
              printf("%d and %d\n", a[i], b[i]);
          }
    } 

    int main(void)
    {
          int number[] = {22, 32, 22, 82, 2};
          int strchars[] = {12, 12, 12, 12, 12};

          int count = sizeof(number) / sizeof(int);
          print_arg(number[], strchars[]);

          return 0;
    }
4

1 回答 1

3

您是否正在尝试编写一个打印数据的函数?

void print_array_args(int a[], int b[], int count)
{
  int i = 0;
  for(i = 0; i < count; i++) {
    printf("%d and %d\n", a[i], b[i]); // You can treat arrays as arrays...
    printf("%d and %d\n", *(a+i), *(b+i)); // ... or as pointers.
  }
} 

void print_pointer_args(int *a, int *b, int count)
{
  int i = 0;
  for (i = 0; i < count; i++) {
    printf("%d and %d\n", a[i], b[i]);     // You can treat pointers as arrays...
    printf("%d and %d\n", *(a+i), *(b+i)); // ... or as pointers.
  }
} 


int main(void)
{
  int number[] = {22, 32, 22, 82, 2};      // You can declare an array...
  int *strchars = malloc(5 * sizeof(int)); // ... or a pointer

  int i;
  for (i = 0; i < 5; i++) {
    strchars[i] = 12;      // You can initialize as an array....
    *(strchars + i) = 12;  // ... or as a pointer
  }

  int strchars[] = {12, 12, 12, 12, 12};
  int count = sizeof(number) / sizeof(int);
  print_array_args(number, strchars, count);
  print_pointer_args(number, strchars, count);
  return 0;
}
于 2012-04-15T05:04:49.857 回答