Tag Archives: C/C++

[Solved] error: invalid operands of types ‘const char [6]‘ and ‘const char [6]‘ to binary ‘operator+‘

 

preface

When using strings in C++, we habitually use + to connect two strings enclosed in "". The error is reported: error: invalid operators of types' const char [6] 'and' const char [6] 'to binary' operator+',


1. Scenarios

	//std::string str = "hello" + "world"; // error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
	//std::string str = std::string("hello") + " world"; // correct
	//std::string str = "hello" + std::string("world"); //correct
	std::string str = "hello"" world"; //correct

    cout << "str=" << str << endl;

When using the+operator to connect two strings wrapped with "", an error occurs. The reason is that in C++, the strings enclosed by "" are regarded as const char* types, rather than string types.

2. Solution

Refer to the explanation on stackoverflow. For details, please read error: invalid operators of types’ const char * ‘and’ const char * ‘to binary’ operator+’

1. Explicitly declare one of them as std::string type (recommended)

std::string str = std::string("hello") + " world";

2. Remove the+and let the compiler splice strings (not recommended)

std::string str = "hello"" world";

Most compilers automatically splice strings enclosed by "", but it is not guaranteed that all compilers are normal. It is recommended to display strings declared as string types and then perform the+operation.


3. Validation

	std::string str1 = std::string("hello") + " world" + "!"; // correct
    std::string str2 = "hello" + std::string(" world") + "!"; //correct
    std::string str3 = "hello"" world" "!"; //correct

    cout << "str1=" << str1 << endl;
    cout << "str2=" << str2 << endl;
    cout << "str3=" << str3 << endl;

[Solved] JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring

JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring

A/k.myapplicatio: java_vm_ext.cc:545] JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring
    java_vm_ext.cc:545]     in call to GetStringUTFChars
    java_vm_ext.cc:545]     from void com.sdk.myapplication.MainActivity.triggerGetStringUTFCharsNPE(java.lang.String, java.lang.String)

The reason for the above message, from a Jni method, refers to the case where the JVM calls the method and the GetStringUTFChars entry jstring is empty, it must not refer specifically to the method body where the GetStringUTFChars call has a NULl pointer, but includes other C/C++ method calls in the method that have a NULL pointer. NULL pointer. So we have to look at the crash stack carefully to quickly locate the place where the NULL pointer is generated to avoid invalid output.

the above example is extracted according to our own business code
the example code is as follows
java

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
        triggerGetStringUTFCharsNPE("hello", null);//introduce a null
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();


    public native void triggerGetStringUTFCharsNPE(String p1, String p2);
}

jni

#include <jni.h>
#include <string>
#include <android/log.h>

static const char* TAG = "Demo";


void nestFunction(JNIEnv *env, jstring p2) {
    //Here p1 is simply passed in via a parameter, but the actual business logic may be obtained by other methods/ways
    const char* pStr = env->GetStringUTFChars(p2, nullptr);
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "pStr:%s", pStr);
    env->ReleaseStringUTFChars(p2, pStr);
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_sdk_myapplication_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}extern "C"
JNIEXPORT void JNICALL
Java_com_sdk_myapplication_MainActivity_triggerGetStringUTFCharsNPE(JNIEnv *env, jobject thiz,
                                                                    jstring p1, jstring p2) {
    const char* pStr1 = env->GetStringUTFChars(p1, nullptr);
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "pStr1:%s", pStr1);
    env->ReleaseStringUTFChars(p1, pStr1);
    //故意让nestFunction产生 JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring
    nestFunction(env, p2);
}

[Solved] std::max() error C2589: ‘(‘ : illegal token on right side of ‘::‘

int max =std::numeric_limits< int>: max();
:: Based on error indicating:

f:\code\cpp\webspider\main. cpp(47): warning C4003: not enough actual parameters for macro ‘max’

f:\code\cpp\webspider\main. cpp(47) : error C2589: ‘(‘ : illegal token on right side of ‘::’

f:\code\cpp\webspider\main. cpp(47) : error C2059: syntax error : ‘::’

Cause: STL’s numeric_limits::max() and VC6 min/max macro conflict.

The problem should be that the macro definitions of the above two header files conflict.

Solution: Use parentheses “()” to avoid precompiler errors. int max = (std::numeric_limits<std::streamsize>::max)(); That’s it.

DevC++ Error: [Error] Id returned 1 exit status [How to Solve]

DEVC + + reports an error [error] ID returned 1 exit status

Cause

The computer in the school computer room always compiles twice and always reports errors

Error reporting prompt

[Error] Id returned 1 exit status

Solution

Premises

First check whether the console window of your program is closed, and then recompile if there is an error. The following scheme is for the case where an error is still reported after closing the window.

Operation

Right click dev C + + icon -> Properties – > Compatibility > Check “run this program as an administrator” open dev C + + –> tools –> compilation options –> code generation/Optimization –> connector –> set “link objective C program” to yes, and switch the compiler in the upper right corner of the dev C + + main page to debug mode (for example, tdm-gcc 4.9.2 64 bit debug) If your computer has a restore card, please place the project and its files on an unprotected disk.

error: ‘CLOCK_MONOTONIC‘ undeclared (first use in this function)

  Error message:

/home/xx/test/main.c: In function ‘main’:
/home/xx/test/main.c:37:21: error: storage size of ‘start’ isn’t known
   37 |     struct timespec start, end; //nanoseconds
      |                     ^~~~~
/home/xx/test/main.c:37:28: error: storage size of ‘end’ isn’t known
   37 |     struct timespec start, end; //nanoseconds
      |                            ^~~
/home/xx/test/main.c:43:5: warning: implicit declaration of function ‘clock_gettime’ [-Wimplicit-function-declaration]
   43 |     clock_gettime(CLOCK_MONOTONIC, &start);
      |     ^~~~~~~~~~~~~
/home/xx/test/main.c:43:19: error: ‘CLOCK_MONOTONIC’ undeclared (first use in this function)
   43 |     clock_gettime(CLOCK_MONOTONIC, &start);
      |                   ^~~~~~~~~~~~~~~
/home/xx/test/main.c:43:19: note: each undeclared identifier is reported only once for each function it appears in
make[2]: *** [CMakeFiles/WBSM4.dir/build.make:63: CMakeFiles/xx.dir/test/main.c.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:78: CMakeFiles/xx.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

Solution:

Add a compiler to the cmakelists.txt file:  

add_compile_options(-D_POSIX_C_SOURCE=199309L) 

Solution source [copyright infringement and deletion]:

c++ – error: ‘CLOCK_ MONOTONIC’ undeclared (first use in this function) – Stack Overflow

error: ‘CLOCK_ Mononic ‘undeclared problem solving_ Whahu 1989 column – CSDN blog

How to Solve Fopen bus error

Bus error (core dumped) occurs in my program, and the error is locked in the fopen part of the code

void dipget(int icdp, int nti, float *dip, char * tanpath)
{
  FILE * dfile;
  char *filename;

  printf("Choose %d from %s\n",icdp, tanpath);
  sprintf(filename, "%s%d.x.dat",tanpath, icdp);
  printf("Open file: %s \n", filename);

  if((dfile = fopen(filename,"rb"))==NULL) // Bus error
  {
    printf("\n Open %s File error\n",filename);
    exit(EXIT_FAILURE);
  }
  fread(dip, sizeof(float), nti, dfile);
  fclose(dfile);
}

Here, you only need to make one step of modification to solve the problem. The reason is very simple. Before using sprintf, you need to allocate a buffer space to it

  char *filename;
  Change to
  char filename[200];

error: initializer element is not constant [How to Solve]

1. Background

C language compilation error: error: initializer element is not constant. The error code is as follows:

    char *info = (char *)malloc(len);
    static char *info_t = info;

The above error is caused by trying to initialize a static variable with the memory pointer allocated by malloc.

2. Error reason

Static variable is a global variable. The value of the global variable cannot be determined at compile time, but at run time (compilation principle). Therefore, the global variable cannot be initialized directly with the return value of malloc at the time of declaration. Replace with the following:

    char *info = (char *)malloc(len);
    static char *info_t; 
    info_t = info;

Compilation passed.

C Language error: two or more data types in declaration specifiers

Libmemcached encountered an error during compilation:

./config.h:632:15: error: two or more data types in declaration specifiers
 #define off_t long int
               ^
./config.h:632:20: error: two or more data types in declaration specifiers
 #define off_t long int
                    ^
./config.h:658:17: error: two or more data types in declaration specifiers
 #define ssize_t int

Since config. H is generated through the automake tool, I don’t know where to find the problem for a while
first write a try. C file:

#define off_t long int
#define ssize_it int
int main() {
	return 1;
}

Can be compiled
multiple attempts have found that it is related to the order of #define. If #define off_ T long int in #define < stdxx.h> Before, an error will be reported, otherwise no error will be reported
via G + + - E - P try. C > XX , you can see:

#define long int __off_t
#define __off_t off_t

If#define off_t long intis ahead of stdxx.h,then use long int to replace off_t:

#define long int __off_t
#define __off_t long int

A loop occurs, so an error will be reported
and if #define off_ T long int after stdxx. H
because you already have #typedef__ off_ t off_ T without execution

In addition, it is found that #include “A.H” can also be used as #include & lt; a.h>, Previously, it was thought that local. H files could only be imported with “” instead of & lt& gt;, Now it is found that with GCC - I. , the directory with – I and include can be used with & lt& gt; Import local H files.

In addition, G + + can get preprocessed output in – E – P X.C, that is, a. CC file. The extern "C" {...} requires that the precompiled output must be compiled by G + +.

Error: expected class name before ‘{‘ token

The error of C + + compiler is as follows:

error: expected class-name before ‘{’ token

When deriving a class, you need to confirm whether it contains the header file of the base class.

If the header file of the base class is included, an error is still reported. As mentioned above, check the header file contained in the base class header file.
For example, all the information about an error is as follows:

aarch64-himix100-linux-g++ -c ./src/base.cpp ./src/host.cpp ./src/main_test.cpp ./src/mcu.cpp ./src/uart1.cpp 
In file included from ./src/../include/main_test.h:6:0,
                 from ./src/../include/base.h:6,
                 from ./src/base.cpp:1:
./src/../include/uart1.h:10:1: error: expected class-name before ‘{’ token
 {
 ^
make: *** [main_test.o] Error 1

There are base classes in the base. H file. Uart1. H is the class to be derived. But look at all the above error information, it appears from the sixth line of base. H. Find line 6, which is the header file of the main function (test program).
Put the header file in line 6 base.cpp It’s OK.

In fact, the above situation should not appear in base. H and base.cpp The header file of the test file should not appear in.

Put the header files (such as # include & lt; pthread. H & gt;) in the corresponding header files (such as base. H).

When testing, you only need to include the base. H file to test the functions in the base.