memset在c不工作 [英] memset in c not working

查看:84
本文介绍了memset在c不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个整数指针设置为零,但它没有将所有寄存器分配给零。



#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 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:

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.


这篇关于memset在c不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆