T
Terence
I usually program in Java, so I am a bit confused about usint pointers in C.
I would really appreciate if someone can help me.
Case 1:
======
// Is this function no good? Since str is a variable created on stack,
// I am assuming it will be deallocated immedately after the function returns,
// right??
char * generateString()
{
char str[100] = "abc";
return str;
}
Case 2:
=====
// str is a pointer pointing to a literal
// Can I use str just like other char arrays?
// How are memory allocated for literals and when are they deallocated??
void main()
{
char * str;
str = "abc";
}
Case 3:
=====
// Similar to case 2 except the literal is returned from a function
// Again, can I use str for anything? When is it deleted from memory??
void main()
{
char * str;
str = generateString();
}
char * generateString()
{
return "abc";
}
Case 4:
=====
// assigning dynamically allocated array to pointer
void main()
{
char * str;
str = generateString();
...
delete str; // I have to delete str at the end, Right?
}
char * generateString()
{
char * charArray = new char[20];
strcpy(charArray, "abc");
return charArray;
}
Case 5:
=====
// str points to a char array created in a C library function
// How was this char array allocated? When will it be deallocated?
// Do I have to delete it explicitly??
void main()
{
char line[20] = "abc#def";
char * str;
str = strtok(line, "#");
delete str; // is this necessary?
// can I modify the content of the array??
}
I would really appreciate if someone can help me.
Case 1:
======
// Is this function no good? Since str is a variable created on stack,
// I am assuming it will be deallocated immedately after the function returns,
// right??
char * generateString()
{
char str[100] = "abc";
return str;
}
Case 2:
=====
// str is a pointer pointing to a literal
// Can I use str just like other char arrays?
// How are memory allocated for literals and when are they deallocated??
void main()
{
char * str;
str = "abc";
}
Case 3:
=====
// Similar to case 2 except the literal is returned from a function
// Again, can I use str for anything? When is it deleted from memory??
void main()
{
char * str;
str = generateString();
}
char * generateString()
{
return "abc";
}
Case 4:
=====
// assigning dynamically allocated array to pointer
void main()
{
char * str;
str = generateString();
...
delete str; // I have to delete str at the end, Right?
}
char * generateString()
{
char * charArray = new char[20];
strcpy(charArray, "abc");
return charArray;
}
Case 5:
=====
// str points to a char array created in a C library function
// How was this char array allocated? When will it be deallocated?
// Do I have to delete it explicitly??
void main()
{
char line[20] = "abc#def";
char * str;
str = strtok(line, "#");
delete str; // is this necessary?
// can I modify the content of the array??
}