简体   繁体   English

如何声明一个空char *并动态增加大小?

[英]How to declare an empty char* and increase the size dynamically?

Let's say I am trying to do the following (this is a sub problem of what I am trying to achieve): 假设我正在尝试执行以下操作(这是我要实现的目标的子问题):

int compareFirstWord(char* sentence, char* compareWord){
      char* temp; int i=-1;
      while(*(sentence+(++i))!=' ') { *(temp+i) = *(sentence+i); }
      return strcmp(temp, compareWord); }

When I ran compareFirstWord("Hi There", "Hi"); 当我运行compareFirstWord("Hi There", "Hi"); , I got error at the copy line. ,复制行出现错误。 It said I was using temp uninitialized. 它说我正在使用temp未初始化。 Then I used char* temp = new char[]; 然后我使用char* temp = new char[]; In this case the function returned 1 and not 0. When I debugged, I saw temp starting with some random characters of length 16 and strcmp fails because of this. 在这种情况下,该函数返回1而不是0。调试时,我看到temp以一些长度为16的随机字符开头,因此strcmp失败。

Is there a way to declare an empty char* and increase the size dynamically only to length and contents of what I need ? 有没有一种方法可以声明一个空char *并仅根据我需要的长度和内容动态地增加大小? Any way to make the function work ? 有什么办法可以使功能起作用? I don't want to use std::string . 我不想使用std::string

In C, you may do: 在C中,您可以执行以下操作:

int compareFirstWord(const char* sentence, const char* compareWord)
{
    while (*compareWord != '\0' && *sentence == *compareWord) {
        ++sentence;
        ++compareWord;
    }
    if (*compareWord == '\0' && (*sentence == '\0' || *sentence == ' ')) {
        return 0;
    }
    return *sentence < *compareWord ? -1 : 1;
}

With std::string , you just have: 使用std::string ,您只有:

int compareFirstWord(const std::string& sentence, const std::string& compareWord)
{
    return sentence.compare(0, sentence.find(" "), compareWord);
}

temp is an uninitialized variable. temp是未初始化的变量。

It looks like you are attempting to extract the first word out of the sentence in your loop. 您似乎正在尝试从循环中的句子中提取第一个单词。

In order to do it this way, you would first have to initialize temp to be at least as long as your sentence. 为了做到这一点,您首先必须将temp初始化为至少与句子一样长。

Also, your sentence may not have a space in it. 另外,您的句子中可能没有空格。 (What about period, \\t, \\r, \\n? Do these matter?) (周期,\\ t,\\ r,\\ n呢?这有关系吗?)

In addition, you must terminate temp with a null character. 此外,您必须以空字符终止temp。

You could try: 您可以尝试:

int len = strlen(sentence);
char* temp = new char[len + 1];
int i = 0;

while(i < len && *(sentence+(i))!=' ') {
   *(temp+i) = *(sentence+i); 
   i++;
}
*(temp+i) = '\0';
int comparable = strcmp(temp, compareWord);
delete temp;
return comparable;

Also consider using isspace(*(sentence+(i))), which will at least catch all whitespace. 还可以考虑使用isspace(*(sentence +(i))),它将至少捕获所有空白。 In general, however, I'd use a library, or STL... Why reinvent the wheel... 但是,总的来说,我会使用一个库或STL ...为什么要重新发明轮子...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM