0

Possible Duplicate:
What happens to memory after ‘\0’ in a C string?

Is it possible to make a pointer's, say, third element NUL ('\0'), thereafter "erasing" the pointers remaining elements?

Community
  • 1
  • 1
Bob John
  • 3,688
  • 14
  • 43
  • 57
  • 1
    Uhh.. "pointers remaining elements" is such a bad construct. What is that phrase *supposed* to mean? Also, `NUL` is used almost exclusively with *characters* and using it in this context is very dubious: `NUL` it is the [ASCII] *character* represented by the integer 0 (aka `'\0'`). –  Oct 24 '12 at 05:38
  • 1
    Can you show us what you have, and what you want the end result to be? – Some programmer dude Oct 24 '12 at 05:39
  • 1
    You're presumably talking about a C-style string rather than pointers in general ? – Paul R Oct 24 '12 at 05:41
  • A pointer doesn't have elements. If you mean a pointer to the start of an array, then the answer is no. You cannot erase elements by placing a zero in front of them. – juanchopanza Oct 24 '12 at 05:47
  • Voting to reopen. As it stands, the question doesn't even mention C strings. – juanchopanza Oct 24 '12 at 06:12
  • The OP does confirm that he is asking about strings in one of his comments below - the question is just not very well worded. – Paul R Oct 24 '12 at 07:38

1 Answers1

3

Assuming you're talking about C-style strings then yes, kind of:

char s[] = "abcdefgh";   // s = "abcdefgh"
                         // (actually contains 9 characters: "abcdefgh\0")

s[3] = '\0';             // s = "abc"
                         // (still contains 9 characters, but now: "abc\0efgh\0")

Note that the characters beyond s[3] haven't magically disappeared at this point - it's just that displaying the string, or passing it to any function that takes a C-style string, results in the string only appearing to contain three characters. You can still do e.g.

s[3] = 'x';              // s = "abcxefgh"
                         // (still contains 9 characters, but now: "abcxefgh\0")
Paul R
  • 208,748
  • 37
  • 389
  • 560