[EDIT]
Ok, so that makes sense, thanks to sharptooth and CashCow. You cannot delete data assigned as const, which makes string literals incomprehensible. Therefore, if I change my initialization to look like this:
char **groups = new char*[2]; char *s1 = new char[10]; char *s2 = new char[10]; char c1 = 'a'; char c2 = 'b'; for(int i = 0; i < 9; i++) { s1[i] = c1; s2[i] = c2; } s1[9] = NULL; s2[9] = NULL; groups[0] = s1; groups[1] = s2;
The hard code for the for loop is so that it only iterates through i = 1 and i = 2, then everything works.
I noticed that int arraySize = sizeof arr / sizeof *arr; only works when an array is assigned to a new [] instead of a local one. This is because my original variable is char ** groups; splits to a pointer, right?
Now I am wondering, is there anyway to say if the data is const?
[ORIGINAL]
I know that arrays and pointers are evil , and that these great things are called vectors and linked lists.
But I'm new when it comes to memory management, and I feel a bit masochistic. Say I'm making an array of C-strings. I know from this question and FAQ-Lite, which must correspond to type a = new type[len]; with delete[] a; . Or I think.
FAQ-Lite talks about managing gear arrays here , but it focuses on matrices, and I'm not sure if this applies to what I'm doing.
This code makes sense to me, but does not fulfill the statement (debugging in Visual Studio 2008) on delete[] a; . What is wrong with this and how can I accomplish this task?
#include <iostream> using namespace std; int main(int argc, char* argv[]) { // Initialize array of C-strings char *groups[] = {"testing1", "testing2"}; // Sanity check cout << groups[0] << endl; cout << groups[1] << endl; // Compute size int arrsize = sizeof groups / sizeof groups[0]; cout << arrsize << endl; for (int i = 0; i < arrsize; i++) { // Since each string is a char array, free string memory with delete[] cout << "Deleting element #" << i << endl; delete[] groups[i]; } cout << "Freeing pointer array." << endl; // Free the memory storing the pointers delete[] groups; return 0; }