LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

allocating dynamic memory for array

Hello All,
My inexperience with C/C++ is apparent in this question.  I need to use dynamic memory to create an array of size iNum.  I will also declare several other array's with size, iNumOfLCM.  Could anyone give me some tips on this subject.  I've tried some stuff already but its not fixing the problem.
    int iNum
    int *dynMem;
    dynMem = (int*)malloc(iNum);
    if (dynMem == NULL)
    {
        exit (EXIT_SUCCESS);
    }
    else
    {
    double dStrength[iNum]={40.34,18.07,44.30,36.64};
    double dA=0;
    double dN=4;
    double dVal[iNum];   
    double dXSum[iNum];
    double dYSum[iNum];
    double dZSum[iNum];

            for(i=0;i+1<=iNum;i++)
            {
                dVal[i] = pow (10, (dStrength[i]-dA)/(dN*10.00));
                dXSum[i] = xLCMs[i]/dVal[i];
                dYSum[i] = yLCMs[i]/dVal[i];
                dZSumr[i] = 1.00/dVal[i];
            }
        free(dynMem);
    }
0 Kudos
Message 1 of 2
(2,908 Views)
Hi,

dynMem is your dynamic array and iNum your number of integer in this array(as I understand)
So, allocating memory for iNum integers would be :

dynMem = (int*)malloc(sizeof(int)*iNum);

sizeof(int) represents size needed in memory for integer type. So iNum*sizeof(int) is the size needed for iNum integers.

I always preferred to use calloc() which is very similar, you jsut do : dynMem = (int*) calloc(iNum,sizeof(int)), it initializes your array with 0.
0 Kudos
Message 2 of 2
(2,905 Views)