簡體   English   中英

從字符串指針 C 獲取更新值

[英]get updated value from string pointer C

在這里把我的頭發撕成 C 串。 我在一個返回 char * 指針的項目中有一個 function。

在使用它之前,我需要更改該字符串的一個元素。 我讀到的所有內容都說只使用 char[] 格式的 char 數組,但這與我當前 state 中的項目不兼容,如果有的話。

我一直在拼命尋找某種方法來將前 n 個字符復制到第二個 char 指針,添加更新的值,然后連接初始指針的其余部分(減去更新的原始值),這不需要 40 行代碼。

為此使用 fgetc 的每次嘗試都未能將 unsigned 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);
.
.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM