相关疑难解决方法(0)

什么是复制和交换习语?

这个成语是什么,什么时候应该使用?它解决了哪些问题?当使用C++ 11时,成语是否会改变?

虽然在许多地方已经提到过,但我们没有任何单一的"它是什么"问题和答案,所以在这里.以下是前面提到的地方的部分列表:

c++ c++-faq copy-constructor assignment-operator copy-and-swap

1907
推荐指数
5
解决办法
34万
查看次数

分配比使用malloc存在的内存更多的内存

每次从stdin读取字母'u'时,此代码段将分配2Gb,并在读取'a'时初始化所有已分配的字符.

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#define bytes 2147483648
using namespace std;
int main()
{
    char input [1];
    vector<char *> activate;
    while(input[0] != 'q')
    {
        gets (input);
        if(input[0] == 'u')
        {
            char *m = (char*)malloc(bytes);
            if(m == NULL) cout << "cant allocate mem" << endl;
            else cout << "ok" << endl;
            activate.push_back(m);
        }
        else if(input[0] == 'a')
        {
            for(int x = 0; x < activate.size(); x++)
            {
                char *m;
                m = activate[x];
                for(unsigned x = 0; x …
Run Code Online (Sandbox Code Playgroud)

c c++ linux memory memory-management

8
推荐指数
3
解决办法
5126
查看次数

三维阵列内存分配中的分段错误错误

int ***a在C中有一个指针变量.我将它作为&aie引用传递给函数.在函数中我得到一个类型的指针变量int ****a.我正在分配这样的内存.

*a=(int***)malloc(no1*sizeof(int**));
some loop from 0 to no1
    (*a)[++l]=(int**)malloc((no1+1)*sizeof(int*));
some loop from 0 to no1
    (*a)[l][h]=(int*)malloc(2*sizeof(int));
Run Code Online (Sandbox Code Playgroud)

这只是我分配内存的时间.没有给出实际的程序; 这里没有错误.但是当我要这样做时:

(*a)[l][h][0]=no1;
Run Code Online (Sandbox Code Playgroud)

它给了我一个"分段错误"错误,我无法理解为什么.

更新: 我写了一个示例程序,它只分配内存.这也给出了"分段错误"错误.

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

void allocate(int ****a)
{
    int i,j,k;
    if(((*a)=(int***)malloc(5*sizeof(int**)))==NULL)
    {
        printf("\nError in allocation of double pointer array\n");
        exit(0);
    }
    for(i=0;i<5;i++)if(((*a)[i]=(int**)malloc(4*sizeof(int*)))==NULL)
    {
        printf("\nError in allocation of single pointer array on index [%d]\n",i);
        exit(0);
    }
    for(i=0;i<5;i++)
        for(j=0;j<4;i++)
            if(((*a)[i][j]=(int*)malloc(3*sizeof(int)))==NULL)
            {
                printf("\nError in allocation of array on index [%d][%d]\n",i,j);
                exit(0);
            }
    for(i=0;i<5;i++)
        for(j=0;j<4;i++) …
Run Code Online (Sandbox Code Playgroud)

c

1
推荐指数
1
解决办法
687
查看次数