Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expected primary-expression before ‘const’ errors

Please help. I am getting many errors.

sub2.cpp: In function ‘int main()’: sub2.cpp:11:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive] sub2.cpp:12:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive] sub2.cpp:16:17: error: expected primary-expression before ‘const’ sub2.cpp:16:36: error: expected primary-expression before ‘const’ sub2.cpp:11:6: warning: unused variable ‘outer’ [-Wunused-variable] sub2.cpp:12:6: warning: unused variable ‘inner’ [-Wunused-variable] make: * [sub2] Error 1

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

char *Subtract(const char *outer, const char *inner);

int main()
{
    char outer = "Bookkepper";
char inner = "keep";

char *word = new char[50];

word = Subtract(const char &outer, const char &inner);

cout << word << endl;
return 0;
}


char *Subtract(const char *outer, const char *inner)
{
int olen = strlen(outer);
int first_occ_idx = -1;
for(int i=0; i < olen; i++){
    if(strncmp(outer+i, inner,strlen(inner)) == 0){
    first_occ_idx = i;
    }
}
if(first_occ_idx == -1){
    return NULL;
}
int ilen = strlen(inner);
int xx = olen - ilen;
char *newstr = new char[xx];
int idx = 0;
for(int i=0; i < first_occ_idx; i++){
    newstr[idx++] = outer[i];
}
for(int i=first_occ_idx+ilen; i < olen; i++){
    newstr[idx++] = outer[i];
}
newstr[idx] = '\0';
return newstr;
}
like image 773
user3330980 Avatar asked Mar 12 '14 03:03

user3330980


1 Answers

In C++, string literals like "Bookkepper" (sic) are const character pointers, it's a little stricter than in C. So it should be:

const char *outer = "Bookkeeper"; // Note also spelling

rather than:

char outer = "Bookkepper";

In addition, you don't include types when calling a function, so:

word = Subtract(const char &outer, const char &inner);

would be better as:

word = Subtract(outer, inner);

Separately (and these are style suggestions only), the correct type for things that represent sizes (such as number of characters in a string) is size_t rather than int.

And it's usually considered good form to clean up all your dynamic memory explicitly so, before returning from main(), you could put:

delete[] word;
like image 178
paxdiablo Avatar answered Oct 06 '22 01:10

paxdiablo