#### Archived

This topic is now archived and is closed to further replies.

# Quickie: inserting chars into a char array

This topic is 6422 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Simple question: How do I insert a character into the char array buf, at say a position denoted by the variable current_position (taking domain 0 to strlen(buf))? r. "The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."

##### Share on other sites
quote:
Original post by Fresh
Simple question:
How do I insert a character into the char array buf, at say a position denoted by the variable current_position (taking domain 0 to strlen(buf))?
r.

1. Create a new array that is one char bigger and copy all the chars up to current_pos.
2. Put in the new char.
3. Copy the rest of the chars.

----------
Andrew

##### Share on other sites
Fine, but the technicalities perplex me; I imagine it''d be something along the lines of:

I want to insert a char into caption[255];

caption[255],
buf[255], are being used without any indirection as follows:

strncpy(buf, caret_position, caption);
caption += caret_position;
strcat(buf, (char)ascii_key);
strcat(buf, caption);
strncpy(caption, strlen(buf),buf);

The problem is with caption += x - this increases the actual value of the char at its index, and I cant figure out what sort of indirection is needed to make this work. Doesn''t anybody have
some sample code that I can look at?
r.

"The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."

##### Share on other sites
Assuming that "buffer" is the destination buffer whose maximal length is "len" and the first "used" entries has been occupied, this simple C function insert the character "c" at position "position" by shifing the remaining entries.

  int InsertChar(char *buffer, int len, int used, int position, char c){ int i; for (i = used; i >= position; i--) buffer[i] = buffer[i - 1]; buffer[i] = c; return(used + 1);}

Returns the new amount of entries in "buffer"...

Hope it helps.

Bye,

Karmalaa

---
"Lifting shadows off a dream once broken
She can turn a drop of water into an ocean"

Edited by - karmalaa on November 24, 2000 4:26:43 PM

##### Share on other sites
Much Obliged.
r.

"The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631433
• Total Posts
3000046
×