memset在c不工作 [英] memset in c not working
问题描述
我试图将一个整数指针设置为零,但它没有将所有寄存器分配给零。
#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));
}
请帮助。
memset
将您指定的字节数设置为您给出的值。所以它正在工作 - 你已经分配了一块nSize
字节长的内存,然后将它们全部设置为零值。
问题我你的循环,坦率地说是一堆垃圾(但是你知道,因为它不会编译,不是吗?)
试试这个:
< pre lang =c ++> for (i = 0 ;我< N; i ++)
{
printf( %d,*(a +一世));
}请记住
a
是int
指针 - 不是字节。所以当你为它添加一个值时,你已经按整数的大小递增了。
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.
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 isnSize
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:
for (i = 0; i < N; i++) { printf("%d ", *(a + i)); }Bear in mind that
a
is anint
pointer - not a byte. So when you add a value to it, you are incrementing by the size of an integer already.
这篇关于memset在c不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!