我应该如何为c字符串char数组分配内存? [英] How should I allocate memory for c-string char array?

查看:107
本文介绍了我应该如何为c字符串char数组分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在尝试学习如何在C ++中使用C字符串时,我遇到了内存分配问题.

这里的想法是创建一个新的字符串,其格式为(s1 + sep + s2) 我正在使用的文本提供了标题,因此无法更改它,但是在尝试设置char str []的大小时遇到​​了问题.我收到一个错误消息,说sLength不是常数,因此不能用于设置数组的大小.我对C ++比较陌生,所以这是一个分为两个部分的问题.

  1. 此策略实际上是为新数组分配内存吗?

  2. 如果无法使用strlen(char *)获得恒定值,如何正确设置数组大小?

    char* concatStrings(char* s1, char* s2, char sep){
        int sLength = strlen(s1) + strlen(s2) + 3; 
        //+1 for char sep +2 for \0 at end of string
        char *str = new char[sLength];
        strcpy (str, s1);
        str [sLength(s1)] = sep;
        strcat (str, s2);
        return str;
    }
    

进行了编辑,所以现在我没有任何编译器错误,但是...

对函数的调用在这里:

    char* str = concatStrings("Here is String one", "Here is String two" , c);
    cout<< str;

我的输出变为:

这里是字符串onec ================== 22221/21/21/21/2/(etc.)/这是字符串两个

解决方案

错误是返回本地数组变量str的地址.其范围在声明的函数concatStrings()中,并且可以控件从函数返回后就无法访问.

要在外部访问它,您需要使用new运算符为堆中的字符串动态分配内存.

char* concatStrings(char* s1, char* s2, char sep){
    int s1Length = strlen(s1);
    int sLength = s1Length + strlen(s2) + 2; 
    // +1 for sep and +1 \0 at end of string
    char* str = new char[sLength];
    strcpy (str, s1);
    // Use strlen here instead of sizeof()
    str [s1Length] = sep;
    str [s1Length + 1] = '\0';
    strcat (str, s2);
    return str;
}

在使用concatStrings返回的字符串完成程序后,应确保通过调用delete

释放内存.

char* str = concatStrings(s1, s2, sep);

// Do something

// Free up memory used by str
delete[] str; 

必须在此处使用delete []而不是删除,否则会导致未定义的行为

我还编辑了concatStrings()函数以使用strlen而不是sizeof

更新:感谢您指出我们只需要执行+2而不是+3,并确保在调用strcat str1和sep之后需要附加'\ 0' >

So in attempting to learn how to use C-Strings in C++, I'm running into issues with memory allocation.

The idea here is that a new string is created of the format (s1 + sep + s2) The text I'm using provided the header, so I can't change that, but I'm running into issues trying to set the size of char str[]. I am getting an error saying that sLength is not constant, and therefore cannot be used to set the size of an array. I'm relatively new to C++ so this is a two part question.

  1. Is this strategy actually allocating memory for the new array?

  2. How do I set the array size correctly if I can't get a constant value using strlen(char*)?

    char* concatStrings(char* s1, char* s2, char sep){
        int sLength = strlen(s1) + strlen(s2) + 3; 
        //+1 for char sep +2 for \0 at end of string
        char *str = new char[sLength];
        strcpy (str, s1);
        str [sLength(s1)] = sep;
        strcat (str, s2);
        return str;
    }
    

Edits made, so now I'm getting no compiler errors but...

The call to the function is here:

    char* str = concatStrings("Here is String one", "Here is String two" , c);
    cout<< str;

My output becomes:

Here is String onec==================22221/21/21/21/2 /(etc.)/ Here is String two

解决方案

Error is returning address of local array variable str. Its scope is within function concatStrings() where you declared, and can't be accessed once control returns from the function.

To access it outside, you need to dynamically allocate memory for the string from the heap using the new operator.

char* concatStrings(char* s1, char* s2, char sep){
    int s1Length = strlen(s1);
    int sLength = s1Length + strlen(s2) + 2; 
    // +1 for sep and +1 \0 at end of string
    char* str = new char[sLength];
    strcpy (str, s1);
    // Use strlen here instead of sizeof()
    str [s1Length] = sep;
    str [s1Length + 1] = '\0';
    strcat (str, s2);
    return str;
}

And after the program is done using the string returned from concatStrings it should ensure to free up the memory by invoking delete

char* str = concatStrings(s1, s2, sep);

// Do something

// Free up memory used by str
delete[] str; 

Must use delete[] here instead of delete, or it results in undefined behaviour

I've also edited the concatStrings() function to use strlen instead of sizeof

UPDATE: Thanks for pointing out that we only need to do +2 and not +3 and for making sure a '\0' needs to be appended after str1 and sep before invoking strcat

这篇关于我应该如何为c字符串char数组分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆