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



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

Answer / 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

More VB Script Interview Questions

Is vbscript a case-sensitive or case-insensitive?

0 Answers  


compare the string without using stringcomp function?

1 Answers   CSS Corp,


What is the difference between do until loop and do while loop?

0 Answers  


Can anyone send me a vb script function for verifying the functionality of active links on a web page

0 Answers   Zensar,


. Program for sorting of numbers in vb script?

2 Answers   Talent Sprint,






how to delete folder test3,test4 and test5 using vbscript?

2 Answers  


how to find number of characters(letter a) in the sentence Rain Rain Go away

4 Answers  


Explain about scrrun.dll?

0 Answers  


How to assign a date value to a variable?

0 Answers  


What is the difference between function and procedure?

0 Answers  


What are the differences between Visual Basic, VBA and VBScript? When would it be appropriate to use one as opposed to another?

1 Answers   Infosys,


hi, How will write a regular expression of date in VB scripting.

1 Answers  


Categories