首页 > 解决方案 > 返回结构数组时遇到问题

问题描述

我是新手,我对类型结构数组有疑问。我真的不知道在哪里指定数组是指针以及在哪里不指定它。因此,无论我在声明和调用涉及此结构数组的函数时使用指针组合,它都不会编译。你知道为什么吗?这是有问题的代码:

typedef struct{
  char letter[7];
} player;

player init_player(){
  player tab[2];

  char letter_player1[4]={' ','a','b','c'};
  char letter_player2[4]={' ','x','y','z'};
  strcpy(tab[1].letter,letter_player1);
  strcpy(tab[2].letter,letter_player2);

  return *tab;
}

void displaying(player tab){
  int position=1;
  printf("%c\n",*tab[1].letter[position]);
}

int main(){
  player tab=init_player(tab);
  displaying(tab);
}

先感谢您 !

标签: c

解决方案


你的代码是怎么错的:

/* required #include (or function prototypes) are not written */

typedef struct{
  char letter[7];
} player;

player init_player(){ /* the return type is not for returning arrays */
  player tab[2];

  /* no terminating null characters are placed, so cannot be used with strcpy() */
  char letter_player1[4]={' ','a','b','c'};
  char letter_player2[4]={' ','x','y','z'};
  strcpy(tab[1].letter,letter_player1);
  strcpy(tab[2].letter,letter_player2); /* only tab[0] and tab[1] are available, tab[2] is out-of-bounds */

  return *tab; /* not the array but only the first element of the array is returned */
}

void displaying(player tab){ /* the argument type is not for getting arrays */
  int position=1;
  /* even if tab were an array(pointer), dereferencing is done via [] operator, so you don't need * here */
  printf("%c\n",*tab[1].letter[position]);
}

int main(){
  player tab=init_player(tab); /* the variable type is not for dealing with arrays */
  displaying(tab);
}

怎么修:

/* add #include */
#include <stdio.h> /* for printf() */
#include <stdlib.h> /* for malloc(), free() and exit() */
#include <string.h> /* for strcpy() */

typedef struct{
  char letter[7];
} player;

/* change return type to return a pointer */
player* init_player(){
  /* you cannot use non-static local array, so instead dynamically allocate an array here */
  player* tab = malloc(sizeof(*tab) * 2);

  /* add terminating null characters (increase array size, and they will be automatically added) */
  char letter_player1[5]={' ','a','b','c'};
  char letter_player2[5]={' ','x','y','z'};

  if (tab == NULL) exit(1); /* for in case the allocation failed */
  /* use tab[0] and tab[1] instead of tab[1] and tab[2] */
  strcpy(tab[0].letter,letter_player1);
  strcpy(tab[1].letter,letter_player2);

  return tab; /* return the (pointer to the first element of) array */
}

/* change argument type to get a pointer */
void displaying(player* tab){
  int position=1;
  /* remove extra * (indirection operator) */
  printf("%c\n",tab[1].letter[position]);
}

int main(){
  /* change variable type to store a pointer */
  player* tab=init_player(tab);
  displaying(tab);
  free(tab); /* the array is dynamically allocated, so clean-up it */
}

您不需要tab传递给的参数init_player(),但它是无害的,因为init_player()可以接受任何参数并且不使用参数。


推荐阅读