编程工具|代码执行过程和内存各区数据状态(数形结合)可视化

以下网页支持Python, JavaScript, C, C++, and Java代码执行过程和内存区数据状态的可视化。

https://pythontutor.com/render.html

先看其内存分区是如何进行数形结合和图示的,将以下代码粘贴入网页的编辑框:

#include #include #include int func(int x, int y);int g = 0;   //全局初始化区char *gp;    //全局未初始化区int func(int x,int y){    int z =10;    printf("ox%08x 
",&z);    return (y+x)*z;}struct Date{    int year;    int month;    int day;};struct Student{    int id;    char *name;    struct Date date;};main(){    struct Student st;   //栈,结构体嵌套    int b;               //栈    char s[] = "abc";    //栈    char *p2;            //栈    char *p3 = "123456"; //123456在常量区,p3在栈上    int x;    static int c=0;         //全局(静态)初始化区    int (*pf)(int,int);     //函数指针声明    gp = (char *)malloc(10); //在堆区分配10字节    p2 = (char *)malloc(10); //在堆区分配20字节    strcpy(gp, "123456");    //123456放在常量区,编译器可能会将它与p3所指向的123456优化成一个地方    printf("1st 局部变量: 
");    x = func(1,2);    pf = func;    x = (*pf)(3,4);    func(5,6);    printf("ox%08x 
",&b);    printf("ox%08x 
",&s);    printf("ox%08x 
",&p2);    printf("ox%08x 
",&x);    printf("ox%08x 
",&pf);        printf("2st 全局(静态)变量 
");    printf("ox%08x 
",&g);    printf("ox%08x 
",&gp);    printf("ox%08x 
",&c);        printf("3st 动态数据区(堆区) 
");    printf("ox%08x 
",&*gp);    printf("ox%08x 
",&*p2);        printf("4st 函数地址: 
");    printf("ox%08x 
",&main);    printf("ox%08x 
",&func);    printf("ox%08x 
",pf);    printf("5st 常量: 
");    printf("ox%08x 
",&*p3);    printf("ox%08x 
",p3);    getchar();}

数形结合的图示:

(以上有点小bug,pf指向的是一个函数指针,并不是结构体变量。)

再来看具体的逐步执行。如有以下桶排序代码,将其粘贴入编辑框:

#include #include void countingSort0(int data[], int n, int c){    int *bucket = (int*)malloc(sizeof(int)*c);    int i,index;    for(i = 0; i < c; i++)        bucket[i] = 0;    for(i = 0; i < n; i++)        bucket[data[i]]++;    for(index = 0,i=0; i < c; i++)        while(bucket[i]-- > 0)            data[index++] = i;    free(bucket);}void countingSort(int arr[],int n){    int max = arr[0];    for(int i=1;i

单击“Visualize Execution”按钮,从下图可以看到,执行过程分为108步,每步的堆、栈内存视图,数据状态显示在右边。左下角提供第一步、上一步、下一步、最后一步按钮,并提供滑块可以直接快速拖动到某一步。

step 20

step 23

step 58

step 91

step 93

step 95

step 108

再看一个实例(单循环求最大值和次大值):

#include using namespace std;void big_2(int arr[],int arrSize,int* first,int* second){    if(arr[0]*second && arr[i] != *first)                *second = arr[i];}int main(){    int arr[]={99,99,99,9,111,88,4,108,3};    int first,second;    big_2(arr,sizeof(arr)/sizeof(*arr),&first,&second);    cout<

数形结合的图示:

-End-

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章