0

this is my code

the error is Segmentation fault,and i can't understand why

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

using namespace std;

int main(int argc, char* argv[])
{
    char* szword[100];

    int i = 0;

    do
    {
        cin >> szword[i];
        cout << szword[i];
        i++;
    }while(strcmp(szword[i - 1], "done"));

    cout << i + 1;

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
wanxin
  • 21
  • 4
  • 7
    What is `char* szword[100];` supposed to be? I think its not what you actually wanted. If you want strings, use `std::string`, `std::vector` for a vector of strings – 463035818_is_not_an_ai Jun 22 '21 at 11:02
  • Does this answer your question? [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) –  Jun 22 '21 at 20:27

2 Answers2

0

For starters neither declaration from headers <cstdio> and <string> is used in your program. So you should remove these directives

#include <cstdio>
#include <string>

You declared an initialized array with the element type char *. Thus this statement

cin >> szword[i];

invokes undefined behavior because the pointer szword[i] has indeterminate value.

Moreover this call even if the argument of the operator will be correct

cin >> szword[i];

can fail. You should check whether it was successful. And I think there is no great sense to output the string "done".

Also in this statement

cout << i + 1;

you are outputting a value that is greater than the number of inputted strings.

If to use character arrays then your program could look the following way

#include <iostream>
#include <cstring>

int main() 
{
    const size_t N = 100;
    char szword[N][N];
    
    size_t i = 0;
    while ( std::cin.getline( szword[i], sizeof( szword[i] ) ) && 
            std::strcmp( szword[i], "done" ) != 0 )
    {
        std::cout << szword[i++] << '\n';
    }
    
    std::cout << i << '\n';
    
    return 0;
} 

The program output might look like

Hello
World
2
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

This below code works fine, if you want to use char *, for C++ string you can use the C++ version

C Version:

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

using namespace std;

int main(int argc, char* argv[])
{
  char *tmp;
  int i = 0;

do
{
    cin >> tmp;
    cout << tmp;
    i++;
}while(strcmp(tmp, "done"));

cout << i + 1;

return 0;
}

C++ Version:

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

using namespace std;

int main(int argc, char* argv[])
{
  string tmp;
  int i = 0;

do
{
    cin >> tmp;
    cout << tmp;
    i++;
}while(tmp != "done"));

cout << i + 1;

return 0;
}