Write a program to resize an array of 5 elements to 4 elements and display all the elements.

Answer Posted / jon doe

C style answer:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
// create array with 5 elements
int *array5 = (int *) calloc(5, sizeof(int));
for(int i = 0; i < 5; ++i) {
array5[i] = rand();
}

// resize array
int *array4 = (int *) realloc(array5, 4 * sizeof(int));

for(int i = 0; i < 4; ++i) {
printf("%d) %d
", i, array4[i]);
}

free(array4);

return EXIT_SUCCESS;
}

C++ style answer:

int main(int argc, char *argv[]) {
// create array with 5 elements
int *array5 = new int[5]();
for(int i = 0; i < 5; ++i) {
array5[i] = rand();
}

// resize array
int *array4 = new int[4];
// copy array via loop. Alternative: use an array-copy function such as memcpy() for C or java.lang.System.arraycopy() for Java
for(int i = 0; i < 4; ++i) {
array4[i] = array5[i];
}
delete[] array5; // not used anymore

// print array
for(int i = 0; i < 4; ++i) {
printf("%d) %d
", i, array4[i]);
}

delete[] array4;

return EXIT_SUCCESS;
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to access array data?

545


Which keyword is used to declare a variable in the vbscript language?

533


What is purpose of scripting.filesystemobject class in vbscript?

629


How to get the length of the string by making use of the string function?

573


Mention when to use function procedures and what are its characteristics?

629






Mention what is select case statement?

548


What is sql loader? Explain the files used by sql loader to load file?

624


How to assign a date value to a variable?

593


How strcomp function works?

626


Which object provide information about a single runtime error in a vbscript?

607


How to declare an array in vbscript?

670


Difference between dim,public and private variables in vb script?

531


What methods are used to create text files and open text files in the vbscript language?

538


Which function is used in the vbscript language to convert the specified expression into a date type value?

528


Illustrate briefly about the different types of statement

2027