0

在这里用C弦扯断我的头发。我在一个项目中有一个函数,它返回一个 char * 指针。

我需要在使用它之前更改该字符串的元素。我读到的所有内容都说只使用具有 char[] 格式的 char 数组,但这与我当前状态下的项目不兼容,如果有的话。

我一直在拼命寻找将前 n 个字符复制到第二个 char 指针的方法,添加更新后的值,然后连接不需要 40 行代码的初始指针的剩余部分(减去更新的原始值)。

为此使用 fgetc 的每次尝试都未能将 unsigned int 写入“更新的指针”。我是否需要将 unsigned int 冲刺到 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;
}
4

1 回答 1

1

如果您只需要将字符串复制到另一个指针,

.
.
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);
.
.
于 2020-05-17T18:12:55.473 回答