Android for JNI (quad)--c array, pointer length, heap memory and stack memory, malloc, student management system

Source: Internet
Author: User

Android for JNI (quad)--c array, pointer length, heap memory and stack memory, malloc, student management system

A few days each write JNI, now the task is more and more heavy, the intensity of the work is a bit high, there are several series of blog to wait for the update, a few books also starving waiting for me to see, GitHub on the two loose open source, basic introductory video is also in the recording, but also to learn new knowledge,
is a challenge, do not know why, recently lazy, it seems to have to add strength, today we continue to extend a little knowledge of C

One. Arrays

C's Array and Java are similar, we write a small program

#include <stdio.h>#include <stdlib.h>Main () {Charc [] ="LGL";//Print the address of each element        printf("% #x \ n", &c[0]);printf("% #x \ n", &c[1]); Aprintf("% #x \ n", &c[2]);printf("% #x \ n", &c[3]);//Let the window stay        intAge;scanf("%d", &age); }

We print out the memory address of each element of this array, and will be surprised to find that the memory address is contiguous

We continue to understand

  //打印C的地址  printf("%#x\n"

We print the address of C

The result is the first memory address, which we summarize

    • The memory space of the array is contiguous
    • An array variable holds the address of a No. 0 element
        //字符数组的地址,就是一个字符的地址         char* p = &c;        printf("第0个元素的值%c\n",*(0));        printf("第0个元素的值%c\n",*(1));        printf("第0个元素的值%c\n",*(2));

Here, we can get LGL, which number is it?
Of course, if it's an int type, you need to shift four units.

Two. Pointer length

Pointer we can save the address, we want to know how long his length, we have to test

#include <stdio.h>    #include <stdlib.h>   main(){      printf("int*的长度是%d\n",sizeof(int*));      printf("double*的长度是%d\n",sizeof(double*));          //让窗口停留       int age ;       scanf("%d",&age);}

Results of the output

The pointer length is 4, because the 32-bit environment, the memory length is 4, enough

Three. heap memory and Stack memory

Java also has a similar argument, we define a variable, in memory to open up a control, that the specific open where, it depends on our type, I draw a picture here, so as to understand

In Java, we define a variable such as int i is in the stack memory to open up the control, Persion P is also, but after we new, the object is in the heap memory. In C, we do not have new, we have a function to request memory malloc, but Java also has other causes and consequences, such as we write the array, in fact, K is in the stack memory, but arrays of objects in the heap memory

The difference between heap and stack:
  • 1. How to Apply

    Stack:
    Automatically assigned by the system. For example, declare a local variable int b; The system automatically opens up space for B in the stack. For example, when the number of calls, the need to save the variable, most obviously in the recursive call, the system automatically allocates a stack of space, LIFO, and then released by the system this space.
    Heap:
    Requires the programmer to apply for it and specify the size, in C with the malloc function
    such as char* P1 = (char*) malloc (10); 14byte
    But note that P1 itself is in the stack.

  • 2 response of the system after application

    Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
    Heap: First of all should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program, in addition, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

  • 3. Restrictions on size of applications

    Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (VC compilation options can be set, in fact, is a stack parameter, the default 2M), if the requested space exceeds the remaining space on the stack, will prompt overflow. Therefore, the space available from the stack is small.
    Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

  • 4. Comparison of application efficiency:

    Stack: Automatically allocated by the system, faster. But programmers can't control it.
    Heap: Memory allocated by Malloc/new, general speed is slow, and prone to memory fragmentation, but the most convenient to use.

  • 5. Storage content in heaps and stacks

    Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack.
    When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.
    Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

  • 6. Recovery of Memory

    The memory allocated on the stack is automatically retracted by the compiler, and the allocated memory on the heap is explicitly retracted through free, otherwise it will cause a memory leak.
    The difference between heap and stack can be seen in the following analogy: \
    Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
    Using the heap is like doing your own favorite dishes, more trouble, but more in line with their own tastes, and great freedom.

Four. malloc

Now that we know, let's use malloc to request heap memory

#include <stdio.h>#include <stdlib.h>Main () {//For example, save three int int is 4 bits so write 12 this 12 bytes memory address is continuous,       //He returns the first address of the heap memory       int* p =malloc(3*sizeof(int));//Assigned value* (P +1) =3;//Print value        printf("%d\n", * (p+1));//= 3?        //Print address        printf("% #x \ n", (p+1));//Let the window stay        intAge;scanf("%d", &age); }

We output the results

How do I release it after the application?

    //释放堆内存    free(p)

We can try to release

#include <stdio.h>#include <stdlib.h>Main () {//For example, save three int int is 4 bits so write 12 this 12 bytes memory address is continuous,       //He returns the first address of the heap memory       int* p =malloc(3*sizeof(int));//Assigned value* (P +1) =3;//Print value        printf("%d\n", * (p+1));//= 3?        //Print address        printf("% #x \ n", (p+1));//Free heap memory         Free(p);//Print value        printf("%d\n", * (p+1));//= 3?        //Print address        printf("% #x \ n", (p+1));//Let the window stay        intAge;scanf("%d", &age); }

We will find that after the memory is released, the value changes, of course, the memory is not released, and p always points to the stack memory

Five. Backend Management system

We here to write a small example, said so tall, is actually a small program, study number management ID applet, we play

The program itself is very simple, is to put the previous few small knowledge in a soft together

#include <stdio.h>#include <stdlib.h>Main () {printf("Please enter class Number:");intCount;scanf("%d", &count);//How many people have a number of school numbers        intI//Application heap memory Save number        int* p =malloc(Count *sizeof(int)); for(i =1; I <= count; i++) {printf("Please enter the student number for%d students:", i);scanf("%d", (p + i-1)); }//Print all the school numbers      for(i =1; I <= count; i++) {printf("The student number for the first%d is%d\n.", i,* (p+i-1)); }intAge;scanf("%d", &age); System"Pause");}

Run and you'll know the effect.

Of course, since we are the management system, insert, we continue to write down
We'll be exposed to a new API here, and we'll see

#include <stdio.h>#include <stdlib.h>Main () {printf("Please enter class Number:");intCount;scanf("%d", &count);//How many people have a number of school numbers        intI//Application heap memory Save number        int* p =malloc(Count *sizeof(int)); for(i =1; I <= count; i++) {printf("Please enter the student number for%d students:", i);scanf("%d", (p + i-1)); }//Insert    printf("Please enter the number of people to insert:");intNewcount;scanf("%d", &newcount);//re-apply heap memory    //Extend new space in existing memory    //Of course, the premise to determine whether to expand, if the memory is taken up, the system will automatically allocate memory    //New memory will copy the old memory and release the old memoryp = realloc (p, (count + newcount) *sizeof(int)); for(i = count+1; I <= Count+newcount; i++) {printf("Please enter the student number for%d students:", i);scanf("%d", (p + i-1)); }//Print all the school numbers      for(i =1; I <= count + newcount; i++) {printf("The student number for the first%d is%d\n.", i,* (p+i-1)); }intAge;scanf("%d", &age); System"Pause");}

The note here is the realloc, the comments are also very clear analysis, we run a bit

OK, learn here for the time being!!

Android for JNI (quad)--c array, pointer length, heap memory and stack memory, malloc, student management system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.