I'm trying to use new but I can't seem to get it right...

in this example I ask how many strings the user would want to input, then ask for each one, then echo them back.

#include<iostream>

using namespace std;

int main(int argc, char** argv){
	
	int num, i;
	char** a;

	cout<< "how many strings? ";
	cin>> num;
	*a = new char[num];
	
	for(i=0;i<num;i++){
		cout<< "enter a string: ";
		cin>> a[i];
	}
	for(i=0;i<num;i++){
		cout<< "string "<< i<< ": "<< a[i]<< endl;
	}

	return 0;

}

I wind up with this (in linux):

how many strings? 3
enter a string: hello
enter a string: there
Segmentation Fault

I tried moving the *s around, putting them on a, taking them back off, etc. nothing has worked... All it did was change when the segfault happened. What am I doing wrong?

--EDIT--

I also tried *a = new char[num][80] and *a = new *char[num] to no avail.
If I use what is written above, and only choose to write 1 string, it works fine.

Recommended Answers

All 3 Replies

why is 'a' a pointer to a pointer?

edit: Hmmm...I see what's you're trying to do.

I have no idea... I just thought **a was the same as a[][], like a two dimensional character array, an array of strings, etc.
I'm not sure what I did wrong, I'm not totally literate with using pointers yet

#include<iostream>

using namespace std;

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

	int num, i;
	char** a;

	cout<< "how many strings? ";
	cin>> num;
	a = new char*[num];

	for(i=0;i<num;i++){
	        a[i] = new char[80];
		cout<< "enter a string: ";
		cin>> a[i];
	}

	for(i=0;i<num;i++)
		cout<< "string "<< i<< ": "<< a[i]<< endl;

	return 0;
}
commented: Beat me to it... very quick :) +10
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.