c - Wanting to deference my array contents to zero. Only first number in array changes to zero -
i new stackoverflow , c , have question. required write program iterate through array, , dereference contents zero. reason, "zero_out_array" change first number in array zero, , not rest. here code, appreciated.
#include <stdio.h> void print_array(int* p_array, int num_elements) { printf("print_array called:\n"); (int = 0; < num_elements; i++) { printf("%d \n", p_array[i]); } } void zero_out_array(int* p_array, int num_elements) { printf("zero_out_array called:\n"); *p_array = 0; (int j = 0; j < num_elements; j++) { printf("%d \n", p_array[j]); } } int main() { int main_array[] = { 15, 24, 33, 42, 51 }; print_array(main_array, 5); zero_out_array(main_array, 5); return 0; }
please consider code modified below:
#include <stdio.h> void print_array(int* p_array, int num_elements) { printf("print_array called:\n"); (int = 0; < num_elements; i++) { printf("%d \n", p_array[i]); } } void zero_out_array(int* p_array, int num_elements) { printf("zero_out_array called:\n"); *p_array = 0; for(int j = 0; j < num_elements; j++) *(p_array+j)=0; (int j = 0; j < num_elements; j++) { printf("%d \n", p_array[j]); } } int main() { int main_array[] = { 15, 24, 33, 42, 51 }; print_array(main_array, 5); zero_out_array(main_array, 5); return 0; }
in above code, have added loop:
for(int j = 0; j < num_elements; j++) *(p_array+j)=0;
*p_array
points first element of array, have used loop change elements. doing *(p_array+j)=0
, iteratively visiting array elements , making them 0.
Comments
Post a Comment