【问题标题】:Error while a pointer it's used inside a function在函数内部使用指针时出错
【发布时间】:2018-04-17 10:48:53
【问题描述】:

在我尝试使用它来显示字符串之前,我有一个 void 函数运行良好。

void Frandom(int tam, char* itens[]){

    int pote[tam];

    srand((time(NULL)));

    for(int i = 0; i < tam; i++){
        int achou;
        do{
            pote[i] = rand() % tam;
            achou = 0;

        for(int j = 0; j < i; j++){

            if(pote[i] == pote[j]){
                achou = 1;
                break;
            }
        }
        }while(achou);
    }

    for(int i = 0; i < tam; i++){
        printf("Tema %d >>> %s\n", pote[i], itens[i]); // I think that here is the problem
    }
}

编译器说期望 char**,但 itens[] 是 char*。我尝试过更改,但不起作用。

另一件事:调用函数。

Frandom(qtd_temas, tnome[qtd_temas]); //works

Frandom(qtd_temas, tnome[]); //doesn't works

【问题讨论】:

  • tnome 是如何在调用者中声明的?
  • 此外,用于打乱整数数组的算法效率极低。它应该是 O(n),但你所拥有的是 O(n**3) 平均值(理论上是无限的)。
  • @Tom Karzes ''char* tnome[qtd_temas];'' 更具体地说:我使用 malloc 设置 itens 的大小(动态分配),然后我有一个分配内存的指针我将收到的每个字符串的空格。好像是:iten [any number] = {"string", "string", "string"}。

标签: c function pointers char void


【解决方案1】:

使用void Frandom(int tam, char itens[]) 代替void Frandom(int tam, char *itens[]) 也使用printf("Tema %d &gt;&gt;&gt; %c\n", pote[i], itens[i]);

【讨论】:

  • 它应该是一个字符串数组,即char *的数组,而不是char的数组。所以这个答案是行不通的。
  • printf("Tema %d &gt;&gt;&gt; %s\n", pote[i], itens[i]) 在这里他应该使用 %c 而不是 %s 然后如果他使用我的解决方案一切都会正常工作
  • 这是对问题的一种解释,但我认为它不正确。我不认为 OP 想要改组字符数组。我认为 OP 想要洗牌一个字符串数组。所以我认为这个答案是不正确的。
  • 谢谢,但它也不起作用。更具体地说:我使用 malloc 设置 itens 的大小(动态分配),然后我有一个指针,为我将收到的每个字符串分配内存空间。好像是:iten [any number] = {"string", "string", "string"}。
猜你喜欢
  • 2016-11-15
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多