Click here to Skip to main content
15,867,949 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have tried to memset an integer pointer to zero, but its not assigning all the register to zero.

#include <stdio.h>
#include <string.h>
#define N 128
int main()
{
int *a;
int nSize = sizeof(int) * N;

a = (int*) malloc(nSize);

//*(a+sizeof(int)*397) = 397;
//*(a+sizeof(int)*396) = 396;
memset(a, 0, nSize);
for(int i=0; i<n;> printf("%d ", *(a+sizeof(int)*i));
}


pls help.
Posted

1 solution

memset sets the number of bytes you specify to the value you have given. So it is working - you have allocated a chunk of memory that is nSize bytes long, then set all of them to the value zero.

The problem is with your loop, which frankly is a load of rubbish (but you know that, because it won't compile, will it?)
Try this:
C++
for (i = 0; i < N; i++)
   {
   printf("%d ", *(a + i));
   }
Bear in mind that a is an int pointer - not a byte. So when you add a value to it, you are incrementing by the size of an integer already.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900