C Programming
1. Write a void function that takes in a 2D array of character and have it print out each array on a new numbered line on the console.
2. Illustrate the stack and the heap allocation. Specify what each variable value holds and where different references are pointing to.
int main()
{
int myarray[3];
myfunction (myarray);
}
int myfunction(int* in)
{
int i;
for (i = 0; i<3; i+= 1)
{
in[i] = i;
}
// illustrate the stack and the heap at this point in the
code
return 0;
}
Hi,
1. Input 2D array of char and getting 1D array as row:
#include<stdio.h>
int main(){
/* 2D array declaration*/
//char disp[2][3];
/* char disp1[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
*/
char disp[2][4] = {
{'a', 'b', 'c', 'd'},
{'f', 'g', 'h', 'i'}
};
//Counter variables for the loop
int i, j;
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%c ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
2)
Stack Allocation :
Example :below program is showing stack allocation ..stack allocation get only by local variables.The allocation happens on contiguous blocks of memory. We call it stack memory allocation because the allocation happens in function call stack.
Stack memory allocated by compiler.
int main()
{
// All these variables get memory
// allocated on stack
int a;
int b[10];
int n = 20;
int c[n];
}
Heap Allocation:
Example: This example shows heap allocation which is on global variables and expression.The memory is allocated during execution of instructions written by programmers.
Heap memory allocation should be handle by programmers himself.he should deallocate memory after use.
int main()
{
// This memory for 10 integers
// is allocated on heap.
int *ptr = new int[10];
}
Your given program heap and stack allocation , commented the program below
int main()
{
int myarray[3]; // allocated on stack
myfunction (myarray);
}
int myfunction(int* in)
{
int i; //created on stack..unintialized
for (i = 0; i<3; i+= 1)
{
in[i] = i;//allocated on heap
}
// Stack (Method myfunction and variables in/i)
// Heap (Values of in/i will be in heap)
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.