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
How to assign a date value to a variable?
If a calulator having 3 buttons (of any number)in 3 of them one is not working properly due to which answer is wrong always. write a script to find out which button is not working properly ?
how to check whether link is disabled in QTP??
What is the scope of a constant declared using public?
Set srchobj=Description.Create() srchobj("type").value="text" srchobj("name").value="q" srchobj("html tag").value="input" browser("micclass:=google").Page("micclass:=google").webedit (srchobj).Set "qtp" what's wrong in my code pls tell me ? the above code working fine and i got my result pass,now i am trying to run the program it shows general run time error why?pls help me i am in learning stage ?
What is dictionary object in vbscript? Explain?
Which operator can be used to check if two numbers are equal or not in vbscript?
How are values assigned to the variables in the vbscript language?
How will you release the memory acquired by an array variable in vbscript?
Which date function is used in the vbscript language to find the difference between the 2 dates?
When to use function procedures and what are its characteristics?
Explain about the support of asp for vb script functionality?
Write a Script for ATM in QTP
Explain vbscript in detail?
Explain about scrrun.dll?