簡體   English   中英

C strcat()給出錯誤的附加字符串

[英]C strcat() gives wrong appended string

我使用單個字符附加了一個字符串,但無法正確顯示。 我不確定我在哪里犯錯。 提前謝謝你的幫助。 該方法的原始應用是從用戶獲取動態輸入。

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

void main(){
    int j;
    char ipch=' ';
    char intext[30]="What is the problem";
    char ipstr[30]="";
    printf("Input char: ");
    j=0;
    while(ipch!='\0'){
        //ipch = getchar();
        ipch = intext[j];
        printf("%c", ipch);
        strcat(ipstr,&ipch);
        j++;
    }
    puts("\n");
    puts(ipstr);
    return;
  }

以下是我得到的輸出。

$ ./a.out 
Input char: What is the problem

What is h  e

 p
oblem

更改

strcat(ipstr,&ipch);

strncat(ipstr, &ipch, 1);

這將強制僅從ipch追加一個字節。 strcat()將繼續追加一些字節,因為要追加的char后面沒有空終止符。 正如其他人所說,strcat可能會在\\0內存中找到某個位置,然后終止,但如果不這樣做,則可能導致segfault。

從聯機幫助頁:

char *strncat(char *dest, const char *src, size_t n);

strncat()函數類似於strcat(),除了

  • 它將最多使用src中的n個字符;
  • 如果src包含n個或更多字符,則無需以null結尾。

strcat要求其第二個參數是指向格式正確的字符串的指針。 &ipch不會指向格式正確的字符串(它指向的字符串的字符序列缺少末尾的空字符)。

您可以使用char ipch[2]=" "; 宣布ipch 在這種情況下,請使用:

  • strcat(ipstr,ipch); 將字符附加到ipstr

  • ipch[0] = intext[j]; 更改要附加的字符。


當您在原始程序&ipch傳遞給strcat ,發生的情況是該函數strcat假定字符串繼續,並讀取內存中的下一個字節。 可能會產生分段錯誤,但也可能發生strcat讀取一些垃圾字符,然后意外找到空字符的情況。

strcat()用於連接字符串...因此僅傳遞一個char指針是不夠的...您必須在該字符后接一個'\\ 0'char,然后傳遞該對象的指針。

/* you must have enough space in string to concatenate things */
char string[100] = "What is the problem";
char *s = "?"; /* a proper '\0' terminated string */
strcat(string, s);
printf("%s\n", string); 

strcat函數用於連接兩個字符串。 不是字符串和字符。 句法-

char *strcat(char *dest, const char *src);

因此您需要將兩個字符串傳遞給strcat函數。

在你的程序中

strcat(ipstr,&ipch);

這不是有效的聲明。 第二個參數ipchchar 你不應該那樣做。 這會導致Segmentation Fault

暫無
暫無

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

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