gpt4 book ai didi

c - C语言解析字符串的意外结果

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:18 25 4
gpt4 key购买 nike

我有以下(简化的)简单应用程序,它是用 line 构建的:

gcc -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -D_GNU_SOURCE      -D_XOPEN_SOURCE -std=c99 -ggdb -O0 main-test.c -L/usr/lib -lm -lglib-2.0 -o main-test

应用程序本身:

#include <stdio.h>
#include <ctype.h>
#include <alloca.h>
#include <glib.h>
#include <glib/gprintf.h>
#include "main.h"

const char *filter(char *original, pt_search_key key) {
const char *mname = "ModelName";
const char *pname = "Product";
const char *delim = " \t";
const char *delim_str = "\"";
const char *end = "\n";
char *value = NULL;
char *token;
char *copied = malloc(sizeof(original)+1);
strcpy(copied, original);

// Just delete initial tabs and whitespaces
while(isblank(*copied)) {
copied++;
continue;
}

token = strsep(&copied, delim);
if (!strcmp(token, mname))
{
token = strsep(&copied, delim_str);
if(!strcmp(token, "")) {
token = strsep(&copied, delim_str);

printf("[before] Token: %s\n", token);
printf("[before] Value: %s\n", value);
//*********** Strange behaviour is here!!! *****//
value = malloc(strlen(token)+1);
printf("[after] Token: %s\n", token);
printf("[after] Value: %s\n", value);

strcpy(value, token);
token = strsep(&copied, end);
while(*token != '\0') {
if(isblank(*token)) {
token++;
continue;
} else {
printf("String contains unexpected symbols:\n");
printf("%s\n", original);
exit(EXIT_FAILURE);
}
}
} else {
printf("String which contains %s is not correct", original);
exit(EXIT_FAILURE);
}
}
return value;
}

int main(int argc, char **argv)
{
filter(" ModelName \"Business Inkjet 1000\"\n", PT_MODELNAME);
return EXIT_SUCCESS;
}

此应用程序给出以下结果:

./main-test 
[before] Token: Business Inkjet 1000
[before] Value: (null)
[after] Token: Business In!
[after] Value: 0

我完全误解了为什么要更改token。对我来说,token 的输出应该是:"Business Inkjet 1000"哪里出错了?

最佳答案

我认为这只是一个拼写错误,但是 sizeof(original) 在这种情况下只是指针的大小。

  char *copied = malloc(sizeof(original)+1);   ??

你需要:

  char *copied = malloc(strlen(original)+1);

关于c - C语言解析字符串的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com