memset an array to 1

后端 未结 4 1982
一生所求
一生所求 2020-12-16 03:10

I am trying to initialize a 2d array with some integer.If I initialize the array to 0 I am getting correct results but If I use some other integer I get some random values.<

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 04:04

    memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111.

    The for loop isn't too much bother:

    int main() {
        int i, val = 1, max = 4;
        int array[max][max];
    
        max = max * max;
    
        for(i = 0 i < max; i++) {
           array[i] = val;
        }
    }
    

提交回复
热议问题