Tech Support > Microsoft Windows > Development Resources > question about malloc
question about malloc
Posted by newbie on May 12th, 2005


I'm trying to allocate memory for an array of integers and set the
values.

int * npt = malloc ( 100 * ( sizeof ( int ) );
*npt = 90;
*npt ++ = 99; // ERROR

int *npt = ( int * ) malloc ( 100 * (sizeof ( int ) );
*npt = 90;
npt ++;
*npt = 99; // ERROR

int * npt [ 100 ] = malloc ( 100 * ( sizeof ( int )); // ERROR

int * npt [ 100 ];
npt [ 0 ] = malloc ( 100 * ( sizeof ( int ) );
*npt [ 0 ] = 99; // ERROR

WTF ! Please help.


Posted by Quentarez on May 12th, 2005


On Wed, 11 May 2005 21:49:07 -0500, newbie wrote:

Here is an example program that demonstrates what you are attempting to do:

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

int main(void)
{
int *n = NULL;

n = malloc(100 * sizeof(int));

if (n != NULL)
{
n[0] = 15;
n[1] = 25;
*(n+2) = 35; /*in this example, *(n+2) is synonymous with n[2]*/
/*etc*/

printf("n[0] = %d\nn[1] = %d\nn[2] or *(n+2) = %d\n",n[0],n[1],n[2]);
}
else
{
printf("malloc failed!\n");
}

return 0;
}

-Quentarez

Posted by Quentarez on May 12th, 2005


On Wed, 11 May 2005 22:47:21 -0600, Quentarez wrote:

Ah. In my haste and distraction I completely forgot to include the free(n);
call to free the memory I allocated.

-Quentarez

Posted by Robert Scott on May 12th, 2005


On Thu, 12 May 2005 18:40:52 -0500, newbie <smedley@hotmail.com>
wrote:

*(n++)=35 does not set the same array element as n[1]=35 because
*(n++)=35 means use n, then increment it afterwards. So it is the
same as n[0]=35; n++;

If you want to increment first, use *(++n)=35;


-Robert Scott
Ypsilanti, Michigan

Posted by newbie on May 12th, 2005


On Wed, 11 May 2005 22:57:06 -0600, Quentarez
<quentarez@cognitiveprocess.com> wrote:

That one can't step the pointer to the desired offset suprises me.
* ( n+1 ) = 35; n [ 1 ] == 35; works fine, but
* ( n++) = 35; == ERROR
Anyway, problem solved. Thanks Quentarez


Posted by Norman Bullen on May 13th, 2005


Robert Scott wrote:
And by changing the value of n, you make it impossible to use n to free
the storage later.

Norm

--
--
To reply, change domain to an adult feline.


Posted by Lucian Wischik on May 18th, 2005


newbie <smedley@hotmail.com> wrote:
Please please please couldn't you just do

#include <vector>
using namespace std;

vector<int> npt(100);
npt[0]=90;
npt[1]=99;
....



--
Lucian


Similar Posts