How to use memset in C

5 Answers

0 votes
#include <stdio.h>
#include <string.h>

#define LEN 5

int main(void) {
	char arr[LEN] = {3, 8, 9, 0, 4};

	memset(arr, 0, LEN);

	for (int i = 0; i < LEN; i++)
		printf("%3d", arr[i]);

    return 0;
}




/*
run:

  0  0  0  0  0

*/

 



answered Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define LEN 5

int main(void) {
    char arr[LEN] = { 3, 8, 9, 0, 4 };

    memset(arr, -1, 3);

    for (int i = 0; i < LEN; i++)
        printf("%3d", arr[i]);

    return 0;
}




/*
run:

 -1 -1 -1  0  4

*/

 



answered Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define LEN 7

int main(void) {
    char arr[LEN] = { 3, 8, 9, 0, 4, 5, 7};

    memset(arr + 2, -1, 3);

    for (int i = 0; i < LEN; i++)
        printf("%3d", arr[i]);

    return 0;
}




/*
run:

  3  8 -1 -1 -1  5  7

*/

 



answered Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define LEN 5

int main(void) {
    int arr[LEN] = { 3, 8, 9, 4, 7}; // int

    memset(arr, 0, LEN);

    for (int i = 0; i < LEN; i++)
        printf("%3d", arr[i]);

    return 0;
}




/*
run:

  0  0  9  4  7

*/

 



answered Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define LEN 5

int main(void) {
    int arr[LEN] = { 3, 8, 9, 4, 7}; // int

    memset(arr, 0, LEN * 4); // int

    for (int i = 0; i < LEN; i++)
        printf("%3d", arr[i]);

    return 0;
}




/*
run:

  0  0  0  0  0

*/

 



answered Nov 11, 2022 by avibootz

Related questions

1 answer 124 views
1 answer 162 views
1 answer 116 views
116 views asked Dec 17, 2022 by avibootz
1 answer 96 views
96 views asked Nov 11, 2022 by avibootz
...