我遇到了這個問題,它詢問是否可以撰寫函式
void insert(char* M, char* T, int i)
從索引 i 開始將字串 T 插入到 M 中,不使用中間字串......我嘗試使用realloc但我認為當原始字串 M 比結果小很多時存在問題,我的理論是realloc改變了字串的地址,以便能夠表示新字串。
例如: M="Wg" T="ron" and i=1; 結果應該是 M="Wrong"。
我正在使用以下代碼:
void insert(char* M,char* T,int i)
{
int l;
l=strlen(M);
M=realloc(M,l strlen(T) 1);
for(int j = l-1; j >= i; j--)
{
M[j strlen(T)]=M[j];
}
for(int j = 0;j < strlen(T); j )
{
M[i j]=T[j];
}
M[l strlen(T)]='\0'; //from what i've tested the string M is correct.
}
并使用此宣告:
char *s=malloc(3);
char *c=malloc(18);
strcpy(s,"as");
strcpy(c,"bcdefghijklmnopqr");
insert(s,c,1); //this example does not work on my machine.
我希望這能澄清這個問題。
那么有沒有辦法做到呢?
uj5u.com熱心網友回復:
使用 的可能實作示例memmove。解釋在評論里
#include <stdio.h>
#include <string.h>
void insertString(char* M, const char* T, size_t index)
{
// ASSUMES there's enough space in M for this operation
// get the original lengths of each string
size_t Mlen = strlen(M);
size_t Tlen = strlen(T);
if (index < Mlen)
{
// M index Tlen is the destination position where the remaining characters in M will start
// M index is the index where T will be inserted
// Mlen-index is the remaining number of characters in M that need to move
memmove(M index Tlen, M index, Mlen-index);
// copy the T string to the space we just created
memcpy(M index, T, Tlen);
// NUL terminate the new string
M[Mlen Tlen] = '\0';
}
else
{
// simply strcat if the index falls outside the range of M
strcat(M, T);
}
}
如果您不被允許使用memmoveor memcpy,則可以很簡單地推出您自己的。
演示
uj5u.com熱心網友回復:
[這不是真正的答案;這是一個對評論來說太復雜的澄清。]
如果你可以假設呼叫者看起來像
char string[6] = "Wg";
insert(string, "ron", 1);
(或string任何大小大于 5的陣列),那么您就可以insert()輕松撰寫。
如果你可以假設呼叫者看起來像
char *string = malloc(3);
strcpy(string, "Wg");
insert(string, "ron", 1);
那么您幾乎可以撰寫insert()usingrealloc來使字串變大,除非您無法回傳string.
如果來電者可能看起來像
char *string = "Wg";
insert(string, "ron", 1);
甚至
char *string = "Wg\0\0\0";
insert(string, "ron", 1);
比你絕對不能寫insert(),因為你不能假設指向的字串是可寫的(在許多平臺上它不會)。
所以,一般來說,答案是:“不”。您無法撰寫insert()在所有情況下都可以使用的通用版本。
還要注意,如果您假設字串在 malloc 的記憶體中并且您可以使用realloc(如我的第二個示例),那么該代碼將不適用于未 malloc 的字串(也就是說,它不會像我的第一個例子那樣對呼叫者起作用),并且它沒有可移植的方式來知道,根據傳遞給它的指標,它是否可以安全使用realloc。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370901.html
