c substring

Code help, language discussions, and software development advice.
Post Reply
Smartweb
Registered User
Posts: 622
Joined: January 15th, 2004, 2:11 am
Contact:

c substring

Post by Smartweb »

C++ is a fairly complicated language, dealing directly with memory management. Here's an example of the memory management put to use. The following functions are named and set up identically to the VB versions with mid, left, and right functions.

Code: Select all

char * left(char * string, int length)
{
  string[length] = 0;
  return string;
}

char * right(char * string, int length)
{
  string += strlen(string) - length;
  return string;
}

char * mid(char * string, int start, int length)
{
  string += start;
  string[length] = 0;
  return string;
}
To use these functions, call them like this:

mid((char*) str, 3, 5)

This would return a substring of the character array str starting at character 3 and ending at 5. Note that the string parameter cannot be a quoted string, only a character array.

It might not make sense how this works to you, but I'll try to get a C++ Memory Pointers tutorial out soon. I'm really bad with deadlines, so I won't set one.

Post any problems or comments.
Thermit
Registered User
Posts: 5
Joined: August 26th, 2004, 5:59 pm
Contact:

Post by Thermit »

Seems to me, you've got an issue with your left and mid functions.

The functions should work, but they have a side-effect. Probably one that was not intended.

The line...

Code: Select all

string[length] = 0; 
Is operating on the original string that was passed in, not a copy.

So, you are actually changing the original string and chopping off part of it when you put the NULL in the middle of the string array.
Smartweb
Registered User
Posts: 622
Joined: January 15th, 2004, 2:11 am
Contact:

Post by Smartweb »

Ah, yes. Thanks for reporting the error.

Fixed code:

Code: Select all

char * left(char * string, int length)
{
  char * string2 = new char[strlen(string)+1];
  strcpy(string2, string);
  string2[length] = 0;
  return string2;
}


char * mid(char * string, int start, int length)
{
  char * string2 = new char[strlen(string)+1];
  string2 += start;
  string2[length] = 0;
  return string2;
}
Thermit
Registered User
Posts: 5
Joined: August 26th, 2004, 5:59 pm
Contact:

Post by Thermit »

Good, that fixes the problem with the unexpected side-effect.

The caller will need to remember to free the returned pointer when they are done to avoid leaking memory. This gets into the whole "pass by value" or "pass by reference" concept, which sometime gets trickier than you might think.

C is like a fast car with no seat belts, powerful but accidents can be bad. ;)
Post Reply