Mark
Mark

Reputation: 8678

Why does this code give segmentation fault?

I wrote a small example to test my understanding of pointers and memory, however I was sure this would work but then it gave seg fault... Any idea what I am doing wrong? Add: I ran this code with other code.

#include <iostream>
using namespace std;

struct Card {

  int a;
  Card(int a) : a(a) { }

};

int main() {

  int **p;
  int **p2;
  int *a;
  int b =3;
  char ** cArray;
  Card **c = new Card*[5];
  for (int i = 0; i<5; i++)
     c[i] = new Card(1);


  a = &b;
  for (int i = 0; i< 10; i++) {
    p = &a;
    //  p2[i] = new int;
    *(cArray + i) = "string";
    cout << cArray[i]<< endl;
  }



  for (int i = 0; i< 10; i++) {
    // p2[i] = a; 
    cout << *a << endl;
  }

}    

Upvotes: 1

Views: 155

Answers (3)

Nikki Locke
Nikki Locke

Reputation: 2941

cArray variable does not seem to be initialised.

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

char ** cArray;

cArray is an unintialized pointer to pointer. You cannot de-reference it.

*(cArray + i) = "string";

Upvotes: 3

red1ynx
red1ynx

Reputation: 3775

cArray uninitialized. Correct this.

char ** cArray = new char*[10];

Upvotes: 1

Related Questions