I created a dynamic array ,and i need to initialize all the members to 0.
How can this be done in C?
int* array;
array = (int*) malloc(n*sizeof(int));
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this case you would use
calloc():It’s safe to assume that all systems now have all zero bits as the representation for zero.§6.2.6.2 guarantees this to work:
It’s also possible to do a combination of
malloc()+memset(), but for reasons discussed in the comments of this answer, it is likely to be more efficient to usecalloc().