hi i was given an assignment to do
i did it but i'm always getting a segmentation fault
i found out where i'm getting the problem but i dont understand why i'm getting the problem

heres the code:
the extra cout's that dont make sense are just to tests to see where the problem is

#include <iostream>
#include <stdlib.h>
using namespace std;

#include "point.h"
                                         
class polygon{
  int n;
  point *points;
public:
  polygon(int n){
    point *points=new point[n];
    this->n=n;
  };
  void init();
  void pprint();
};

void polygon::init(){
  cout<<"n"<<n<<endl;   //
  for(int i=0;i<n;i++){
    cout<<"hehe"<<endl;  //
    points[i].set(rand()%101,rand()%101);   ////this is the place with the segmentation fault
    cout<<"blah"<<endl;  //
  }
};

void polygon::pprint(){
  cout<<"n"<<n<<endl;  //
  for(int i=0;i<n;i++){
    cout<<"bsde"<<endl;  //
    points[i].print();     /////since there is a problem above then this part is likely to have a segmentation fault as well
    cout<<"aeetr"<<endl;  //
  }
};

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

  if(argc!=2){
    cout<<"wrong number of arguments"<<endl;
    return 1;
  }

  int a=atoi(argv[1]);

  polygon p(a);

  p.init();
  cout<<"pinit done"<<endl;  //

  p.pprint();
  cout<<"pprint done"<<endl;  //

  cout<<"end bye bye"<<endl;  //

  return 0;
};

there are no problems with the point.h point.cpp part but if you need it say so and i'll post that up later

thank you for your help in advance

Recommended Answers

All 4 Replies

could you please post the point class code.

this is point.h code

#ifndef POINT_H
#define POINT_H

class point{
  int x,y;
 public:
  int getX() const;
  int getY() const;
  void set(int x,int y);
  void print() const;
};

#endif

the code for point.cpp

#include <iostream>
using namespace std;

#include "point.h"

int point::getX() const{return x;}
int point::getY() const{return y;}
void point::set(int x,int y){
  this->x=x;
  this->y=y;
}
void point::print() const{
  cout<<"("<<x<<", "<<y<<")\n";
}
class polygon{
  int n;
  point *points;
public:
  polygon(int n){
    point *points=new point[n];
    this->n=n;
  };

At the line 6 you initialize a local variable points . The member points remains uninitialized.

ahhhhhh didnt notice that >.<
thank you for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.