【问题标题】:Passing Array to function using double pointer使用双指针将数组传递给函数
【发布时间】:2018-08-19 17:43:55
【问题描述】:

我试图通过下面代码中的函数更新数组,这很好。

char bookCategory[][MAX_CATEGORY_NAME_LENGTH] = {"Computer", "Electronics", "Electrical", "Civil", "Mechnnical", "Architecture"};

uint8_t getCategoryNumAndName(char* catName, uint8_t choice)
{
    choice = choice - 0x30 - 1;  /** Category starts from 1 on the screen */
    if (choice >= (sizeof (bookCategory) / sizeof (bookCategory[0])))
    {
        //catName = NULL;
        return (0xff);
    }
    else
    {
        strcpy(catName,bookCategory[choice]);
        //catName = bookCategory[choice];
        return(choice);
    }

}

void addBooks(void)
{

// Some code here

char categoryName[30];
uint8_t catNumber;
catNumber = getCategoryNumAndName(categoryName, choice);

// Some code here
}

但我想到了使用双指针而不是使用 strcpy()。我尝试了下面的代码,但出现不兼容的指针类型错误。如何从 addBooks() 调用下面代码中的 getCategoryNumAndName()?

uint8_t getCategoryNumAndName(char** catName, uint8_t choice)
{
    choice = choice - 0x30 - 1;  /** Category starts from 1 on the screen */
    if (choice >= (sizeof (bookCategory) / sizeof (bookCategory[0])))
    {
        *catName = NULL;
        return (0xff);
    }
    else
    {
        //strcpy(catName,bookCategory[choice]);
        *catName = bookCategory[choice];
        return(choice);
    }

}

void addBooks(void)
    {

    // Some code here

    char categoryName[30];
    uint8_t catNumber;
    catNumber = getCategoryNumAndName(&categoryName, choice);

    // Some code here
    }

【问题讨论】:

    标签: c arrays double-pointer


    【解决方案1】:

    您只能将指针地址传递给getCategoryNumAndName 函数而不是数组地址。 您可以执行以下操作。

        char *categoryName = NULL;
        catNumber = getCategoryNumAndName(&categoryName, choice);
    

    确保在取消引用之前将内存分配给getCategoryNumAndName 中的categoryName

    【讨论】:

      【解决方案2】:

      要强制代码工作,您需要将 categoryName 转换为 char**。但是阅读您的代码,您似乎只想移动指针?类别名称不需要固定大小的数组。只需使用指针:

      char* categoryName;
      

      【讨论】:

      • 只有在真正知道它在做什么的情况下才应该使用演员表。对于此代码,演员表是绝对错误的操作者并且绝对是恶意的。使用正确的类型,强制转换不能修复类型错误!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2013-02-15
      • 1970-01-01
      • 2019-02-19
      • 2011-05-19
      • 1970-01-01
      相关资源
      最近更新 更多