简体   繁体   English

错误:C++ 中的“]”标记之前的预期主表达式

[英]Error: expected primary-expression before ']' token in C++

I'm trying to create something similar to string.find with vectors c++98 , but I can't fix this error.我正在尝试使用向量c++98创建类似于string.find的内容,但我无法修复此错误。 I have simplified the code and left only the error.我已经简化了代码,只留下了错误。 If I can get help on how to achieve this.如果我能就如何实现这一目标获得帮助。

#include <iostream>
#define MAX 99999
using namespace std;

int free_pos (int v[]);
int find_line (int v[], int pos);

int main() {
   char text[MAX];
   int loc_key[MAX],start_line[MAX]; //

   for(int i=0; i<free_pos(loc_key);i++) {
       cout << "Line: " << i+1;
       int pos = find_line(start_line[],loc_key[i]); //Here is the error
       for(int j=start_line[pos];j<start_line[pos+1];j++) {
            cout<<text[j];
       }
       cout<<endl;
   }
   return 0;
}

int free_pos (int v[]) {
    for(int i=0;i<MAX;i++){
        if(v[i] == 0)
            return i;
    }
    return 99;
}

int find_line (int v[], int pos) {
    for(int i=0; i<free_pos(v); i++) {
        if(v[i]==pos)
            return v[i];
        if(v[i]< pos)
            return v[i-1];
    }
}

Your both functions你的两个功能

int free_pos (int v[]);
int find_line (int v[], int pos);

take arrays as an input, but then you try to call int pos = find_line(start_line[],loc_key[i]);将数组作为输入,然后尝试调用int pos = find_line(start_line[],loc_key[i]); , which should take the name of an array only , as it is the name which is known by the program as an array. ,它应该采用数组的名称,因为它是程序称为数组的名称。 You can easier (in my opinion) get it, if you write both of these functions following way:如果您按照以下方式编写这两个函数,您可以更容易(在我看来)得到它:

int free_pos (int* v);
int find_line (int* v, int pos);

They do the same job as your functions, but you can see that their arguments are: an int pointer (array) and an int.它们与您的函数执行相同的工作,但您可以看到它们的参数是:一个 int 指针(数组)和一个 int。 Then, calling the function needs only the int pointer, which in your case is start_line , and the integer loc_key[i] .然后,调用该函数只需要 int 指针(在您的情况下是start_line )和整数loc_key[i] If you still have problems understanding it, you could read about dynamic memory allocation of arrays, which is done as: int* arr; arr = new int[your_size];如果你在理解它时仍然有问题,你可以阅读数组的动态内存分配,它是这样完成的: int* arr; arr = new int[your_size]; int* arr; arr = new int[your_size]; - I think it is clearer while thinking that way. - 这样想就更清楚了。

#include<bits/stdc++.h>
using namespace std;
int max(int arr[],int n){
maximum=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]>maximum){
maximum=arr[i]}}
return maximum;}

int main(){
int size;
cin>>size;
for(int i=0;i<size;i++){
cin>>arr[i]}
cout<<max(arr,size);
return 0;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM