Pointers and Arrays in C

From: Terence (findty_at_hotmail.com)
Date: 10/31/03


Date: Thu, 30 Oct 2003 23:34:07 GMT

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??
}



Relevant Pages

  • Pointers and Arrays in C
    ... Since str is a variable created on stack, ... void main ... // assigning dynamically allocated array to pointer ... // str points to a char array created in a C library function ...
    (comp.lang.cpp)
  • Pointers and Arrays in C??
    ... Since str is a variable created on stack, ... void main ... // assigning dynamically allocated array to pointer ... // str points to a char array created in a C library function ...
    (comp.lang.c)
  • Re: How to transfer an address value without using pointers
    ... void send; ... void send(char *str) ... Exactly the code above gives you a segmentation fault? ... pointer to an array with automatic storage duration. ...
    (comp.lang.c)
  • Re: How to transfer an address value without using pointers
    ... void send; ... In main sprintf is used to convert the pointer value returned by ... the send function which accesses 's' as the local 'str'. ... to use an unsigned char array instead of a plain char one for 's.' ...
    (comp.lang.c)
  • Re: Random String
    ... void RH_Random(unsigned char *str, size_t len) ... As long as it is a char array yes. ... Are you ever going to initialize something else to a string? ...
    (comp.lang.c)