在这里,我用C弦撕掉头发。我在项目中有一个函数,该函数返回char *指针。
在使用它之前,我需要更改该字符串的元素。我读到的所有内容都只是使用char []格式的char数组,但这与我项目的当前状态不兼容,如果有的话。
我拼命寻找某种方式来将前n个字符复制到第二个char指针,添加更新后的值,然后合并不占用40行代码的初始指针的其余部分(减去更新的原始值)。 。
每次尝试使用fgetc都无法将未签名的int写入“更新的指针”。我是否需要将unsigned int sprintf放入char缓冲区或其他内容?为什么感觉如此荒唐复杂?
在所需行为的第一步中尝试失败的示例:
int main() {
char *s;
s = "babado = lubidee = popop =pew";
char * s1;
s1 = malloc(10);
memset(s1,'0',9);
strcpy(s1,fgetc(s));
for (int i = 0; i<4; i++){
strcat(s1,fgetc(s));
}
printf("%s",s1);
return 0;
}
如果只需要将字符串复制到另一个指针,
.
.
char *newptr;
//Allocate memory for new pointer
int i=0;
while(i<n) //first n characters
*(newptr+i)=*(returnedptr+i);. //returnedptr is your initial ptr
//Add new value
i++;
while( *(returnedptr+i)!='\0')
*(newptr+i)=*(returnedptr+i);
.
.