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
Explain about vb script?
how to answer "TELL ME ABOUT UR SELF" as exp.person. whr to start and whr to stop. can anyone tel me
Write a code to print numbers from 5 to 0?
How to delete a cookie using vbscript?
Explain vbscript in detail?
How to write VB script for login module?
Mention how you can call vbscript functions?
How will you format a number in percetage format in vbscript?
What are the special sub-types in vbscript?
What are the advantages of vbscript?
How are comments handled in the vbscript language?
What is the difference between VBScript and JavaScript?
1.I want to establish connection with excel and also want to fetch the data using SQL queries. 2.the code should be written in such a way that in future if I want to migrate from excel to MS excess database , then there should be minimal changes.
In html file what is an ideal position to include vbscript?
Give me sm ideas to write Vbscripts abt protocol testing abilash700@gmail.com.