Why is memset() incorrectly initializing int?

后端 未结 9 1115
迷失自我
迷失自我 2020-11-28 09:56

Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf(\"%d\", grid         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 10:23

    You haven't actually said what you want your program to do.

    Assuming that you want to set each of the first 100 elements of grid to 5 (and ignoring the 100 vs. 110 discrepancy), just do this:

    for (int i = 0; i < 100; i ++) {
        grid[i] = 5;
    }
    

    I understand that you're concerned about speed, but your concern is probably misplaced. On the one hand, memset() is likely to be optimized and therefore faster than a simple loop. On the other hand, the optimization is likely to consist of writing more than one byte at a time, which is what this loop does. On the other other hand, memset() is a loop anyway; writing the loop explicitly rather than burying it in a function call doesn't change that. On the other other other hand, even if the loop is slow, it's not likely to matter; concentrate on writing clear code, and think about optimizing it if actual measurements indicate that there's a significant performance issue.

    You've spent many orders of magnitude more time writing the question than your computer will spend setting grid.

    Finally, before I run out of hands (too late!), it doesn't matter how fast memset() is if it doesn't do what you want. (Not setting grid at all is even faster!)

提交回复
热议问题