简体   繁体   中英

segmentation fault (core dumped) when I try cout a const char *[i], what is the issue?

g++ compiler says:

segmentation fault (core dumped)

when this code is running:

#include <iostream>
using namespace std;

int main(){

const char *constantChars[3], *variableChars[3];
long int numbers[3];

for(int i=0; i<4; i++){
    constantChars[i] = "hello number: ";
    numbers[i] = i;
    variableChars[i] = (const char *) numbers[i];

    cout<<constantChars[i]<<variableChars[i]<<endl;
}

return 0;}

it crash when cout<<variableChars[i]<<endl in my for loop.

Change:

variableChars[i] = (const char *) numbers[i];

to:

variableChars[i] = (const char *)(&numbers[i]);

The problem is with length of the arrays that you have declared. You have set the length to be 3 so it should be used for index from 0 to 2 whereas in your program you are using index from 0 to 3.

Just increase the length of all the arrays to 4, it will solve your problem.

Change:

const char *constantChars[3], *variableChars[3];
long int numbers[3];

to:

const char *constantChars[4], *variableChars[4];
long int numbers[4];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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