【问题标题】:Problem with c++ function - error: incompatible types in assignment of ‘int’ to ‘int [n]’c++ 函数的问题 - 错误:将“int”分配给“int [n]”时的类型不兼容
【发布时间】:2020-12-10 10:08:23
【问题描述】:

我想在 C++ 中创建一个名为“losowanie”的函数,这个函数应该在 0-n 之间随机 n 个数字。当我调用这个函数时,我得到:

error: incompatible types in assignment of ‘int’ to ‘int [n]’

这是我的代码:

 #include <iostream>
    #include <stdlib.h>
    #include <time.h>
   
using namespace std;

int losowanie (int tab[], int n) {
    for(int i = 0;i<n; i++) {
        tab[i] = rand() % n + 1;
        cout<<tab[i]<<endl;
    }
}

int main()
{
    int n = -1;
    
    while(n<0 || n>50) {
        cout<<"Give number (  0 - 50)"<<endl;
        cin>>n;
    }
    
    int tab[n];
    tab = losowanie(tab, n); //here is error
    
    return true;
}

【问题讨论】:

  • 看起来losowanie 应该就地填充tab 数组。你认为它应该返回什么?
  • 正如@BoBTFish 所说,losowanie 就地填充数组,只需删除对函数结果的 tab 变量的附加分配。 losowanie(tab, n); 同样,该函数应该返回一个 int (当前不返回任何内容),并且您的选项卡是 int 数组

标签: c++ variable-assignment function-declaration variable-length-array incompatibletypeerror


【解决方案1】:

对于像这样的初学者可变长度数组

int tab[n];

不是标准的 C++ 功能。而是使用标准容器std::vector

这个while循环

while(n<0 || n>50) {

允许为变量n 输入值0。但是你不能声明一个包含 0 个元素的可变长度数组。

函数losowanie

int losowanie (int tab[], int n) {
    for(int i = 0;i<n; i++) {
        tab[i] = rand() % n + 1;
        cout<<tab[i]<<endl;
    }
}

返回类型为int,但不返回任何内容。

在这个赋值语句中

tab = losowanie(tab, n);

左操作数的类型为int[n],而函数的返回类型为int。所以编译器会发出一个错误,因为这个语句没有意义。数组没有赋值运算符。

您可以将函数的类型从 int 更改为 void 并删除赋值语句。

您还应该使用标准 C 函数 srand 来获取不同的随机数序列。

【讨论】:

    【解决方案2】:

    losowanie 返回 int,但 tab 是一个数组。 将 losowanie 变为 void 函数就足够了。

    void losowanie (int tab[], int n) {
    for(int i = 0;i<n; i++) {
        tab[i] = rand() % n + 1;
        cout<<tab[i]<<endl;
    }
    

    而且,主要是:

    int tab[n];
    losowanie(tab, n);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2016-01-01
      • 2018-11-12
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多