Reputation:
This is a question regarding a pointer to a string versus pointers (plural) to an array of strings. Here is the code - please see comments for the problem:
int main(int argc, char** argv) {
// Here, we're just loading each string into an incrementing pointer and printing as we go. It's not an array of pointers. This works fine.
char* dumb = NULL;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
dumb = argv[i];
cout << dumb << endl;
dumb++;
}
// Next we'll try to load the strings into an array of pointers, and print them out. This causes an error (see below).
char** dumber = NULL;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
*(dumber + i) = argv[i];
cout << dumber[i] << endl;
}
return 0
}
Unhandled exception at 0x001899F7 in Testing.exe: 0xC0000005 : Access violation writing location 0x00000000.
Could someone please correct me?
Upvotes: 0
Views: 98
Reputation:
This is what I ended up with. Perhaps it'll be helpful to other rookies, so I thought I'd post it. It finishes by deallocating the memory allotted to the dumber array, which I understand is a good thing to do.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
// int main(int argc, char** argv) { // An alternative.
// Just loading each string into the same pointer and printing as we go.
// It's not an array of pointers.
char* dumb;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
dumb = argv[i];
cout << dumb << endl;
}
// Next we'll load the strings into an array of pointers, and print them out.
char** dumber = new char* [argc];
cout << argc << endl;
for (int i = 0; i < argc; i++) {
*(dumber + i) = argv[i];
cout << dumber[i] << endl;
}
// Deallocate the memory dynamically assigned by the 'new' operator for the
// pointer array.
delete[] dumber;
dumber = 0;
cin.get();
return 0;
}
Upvotes: 1
Reputation: 883
add this line to the code :
dumber = malloc(100); // adjust the size as per your requirements
Since you have not allocated any space to the "dumber" thus every time you try to
write a new string, you are writing it at the location 0x00000000, writing at this
location results in access violation since no process is allowed to write at this address.
This address is specifically reserved for the null pointer.
Upvotes: 1
Reputation: 1019
Where is your array of pointer?
char** dumber =NULL;
Is just pointer to a 'pointer to char' not an array of pointers. You need
char** dumber = new char*[argc];
Upvotes: 2