Hi, I am still very new to C++ and need help with new/delete, I am posting what I wasn't able to find answers for on msn search or by myself after hours of testing..
1. Am I using new/delete correctly?
char hehe[1024];
memset(hehe,0,sizeof(hehe));
sprintf(hehe,"Some Text");
char *testx;
int testxlen = strlen(hehe) + 1;
testx = new char[testxlen];
for (size_t i = 0; i < testxlen; ++i) testx[i]=hehe[i];
memset(hehe,0,sizeof(hehe));
sprintf(hehe,"testx:%s\nsize:%d\nlen:%d\n",testx,sizeof(testx),strlen(testx));
MessageBox(GetActiveWindow(),hehe,"Checking",MB_OK);
//the size returns 4.. and the len returns 9, all my text is there..
//but why is the size of the array smaller then the ammount of text? did i do something wrong?
delete[] testx;
memset(hehe,0,sizeof(hehe));
sprintf(hehe,"testx:%s\nsize:%d\nlen:%d\n",testx,sizeof(testx),strlen(testx));
MessageBox(GetActiveWindow(),hehe,"Checking",MB_OK);
//the memory is deleted (correct?) then why does the size of the array still say 4?
2. Can I use memcpy() on a char created with new? How? (clueless, is it safe?)
3. If I have a global variable that is a pointer (char *haha), can I use new to allocate memory (and use delete[] to remove memory even if it hasn't been allocated first) and have haha point to it? Such as:
char *haha;
int main(void)
{
char hehe[1024];
memset(hehe,0,sizeof(hehe));
sprintf(hehe,"Some Text");
while (1) {
MessageBox(GetActiveWindow(),haha,"Checking",MB_OK);
delete[] haha;//is it safe to use this before memory is allicated? if haha points to nothing (when the program first starts and nothing has been allocated)
MessageBox(GetActiveWindow(),haha,"Checking2",MB_OK);
int testxlen = strlen(hehe) + 1;
haha = new char[testxlen];
for (size_t g = 0; g < testxlen; ++g) haha[g]=hehe[g];
Sleep(1000);
}
delete[] haha;
return 0;
}
4. Can anyone provide me with links that they found helpful with new/delete?
Anyone who is able to help me (Links, Comments, Code), thanks in advance.. I am making an attempt and wouldnt post unless I couldn't come up with an answer after trying/searching for hours on end..