[英]strcat with char pointers
因此,我的問題很簡單,我想創建一個函數來分離文件中的單詞並解析這些單詞,並為這些單詞創建一個特殊的想法,但是,當我嘗試分離標記時,strcat出現錯誤:
看一下代碼:
#include <stdio.h>
#include <string>
#include <Windows.h>
using namespace std;
bool compile(FILE *fp)
{
char c;
char token[256];
bool _return = false;
while ((c = getc(fp)) != EOF)
{
if(isalpha(c))
{
// The error is here
strcat(token, (char*)c);
printf("%c\n", c);
}
else
{
printf("----> %c\n", c);
}
}
printf("%s\n", token);
return _return;
}
int main()
{
char *filename = "test.in";
FILE *fp = fopen(filename, "rb");
if(!fp)
{
return 1;
}
if(!compile(fp))
{
printf("ERROR...\n");
}
fclose(fp);
}
代碼可以正常構建,但是,當我調試時,調試器轉到strcat.asm文件:(因此,我的錯誤在哪里,感謝您的幫助。(:
-0-0-0-0-0-0-0-0-0->編輯而且,當我將strcat更改為:
strcat(token, &c)
我從調試器收到此錯誤:
APP.exe中0x20E801F2的未處理異常:0xC0000005:訪問沖突(參數:0x00000008)。
這是錯誤的:
strcat(token, (char *) c);
變量c
不是字符串,而只是一個字符。 強制轉換為(char *)
僅掩蓋了編譯器錯誤。
如果您想一次向一個字符串添加字符,
std::size_t pos = 0;
char buf[256];
// ...
if (isalpha(c)) {
assert(pos < sizeof(buf));
buf[pos++] = c;
}
// ...
assert(pos < sizeof(buf));
buf[pos] = '\0';
printf("buf = %s\n", buf);
或者,您知道,通過簡單的方法即可:
#include <string>
std::string s;
// ...
if (isalpha(c)) {
s += c;
}
// ...
printf("buf = %s\n", s.c_str());
不要去調試strcat()
的內部。 如果您的程序在strcat()
內部崩潰,則是調用函數中的錯誤。 (甚至根本不調用strcat()
通常是一個錯誤。)
strcat
期望以null結尾的字符串; 您不能將指針傳遞給單個字符並期望其正常工作。
更換
strcat(token, (char*)c);
與
char tmp[2];
tmp[0] = c;
tmp[1] = '\0';
strcat(token, tmp);
使它工作。
您還需要將token[0]
設置為零,以避免由於未初始化而導致未定義的行為。
當將c
為char *
,您要將char *
任何值(例如十六進制的100
)轉換為內存地址( 0x100
),然后在該內存地址中查找字符串。 難怪它不起作用! 您需要先將字符轉換為字符串,然后再將其彈出到strcat
。
三件事:
char c
轉換為(char *) c
,是說c是內存地址。 實際上,這是一個價值。 您可能想要的是對字符&c
的引用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.