Deleting[] a char*[]

When I run the following code, the compiler tells me
"Debug Assertion Failed!... Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)..."


The compiler breaks at the "delete[]c[n];" What's going on?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "stdafx.h"
#include <iostream>

char* c [2]={NULL};

void main(){
	c[0]=new char[]="1 st";
	c[1]=new char[]="2 nd";

	std::cout<<c[0]<<'\n'<<c[1];

	for(int n=0;n<2;n++)
		delete[]c[n];//PROBLEM

	std::cin.get();
}
The way you are initializing c[0] and c[1] is not correct, try replacing lines 7-8 with this:
1
2
3
4
c[0]=new char[5];// 5 == number of characters in "1 st"
c[1]=new char[5];
strcpy(c[0],"1 st");//set c[0] to "1 st"
strcpy(c[1],"2 nd");
Last edited on
Ah, right... I see. So I was setting the value of the pointers to "1 st" and "2 nd". Thanks.
But then there's another problem: what does it mean to say "c[0]=new char[]"?
And how did cout know to print "1 st" rather than "0x03cb6b45" or what ever the four byte hexadecimal representation is?
Since c is an array of arrays, it tells the compiler that the first element of c is a new character array with an unknown size. It didn't "know"...it's just that since c[0] is an array of chars, it will print out the array for you.
new char[] doesn't mean anything. It's not valid syntax.
Ah, so you have to do new char*?
You have to create a variable of type char and then store that. new char is Java syntax
new char is Java syntax

What? Says who?
new char (no []), new char*, new char**, new char***, ad nauseam, are all valid in C++.
You can create arrays of things, of any size as long as the size is >0. If the size is 1, the [] can be omitted. The [] can never be empty for dynamic allocation.
Topic archived. No new replies allowed.