C中的动态申请函数malloc的使用

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void func(char* p1, char* p2, char* s)
{
    s = (int*)malloc(sizeof(int));
    s = *p1 + *(p2++);
}

int main()
{
    int a[2] = { 1,2 };
    int b[2] = { 10,20 };
    char *s = a;
    func(a, b, s);
    printf("%d\n",*s);
    return 0;
}
 

输出 

1

为什么输出的是1,而不是11

s = (int*)malloc(sizeof(int));把这句删了就可能是11了。因为你给s分配了新的内存地址,在新的内存上进行加法操作,原内存地址上的值不变。话说你这能编译通过?不科学

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void func(int* p1, int* p2, int** s)
{
    *s = (int*)malloc(sizeof(int));
    **s = *p1 + *(p2++);
}

int main()
{
    int a[2] = { 1,2 };
    int b[2] = { 10,20 };
    int *s = a;
    func(a, b, &s);
    printf("%d\n",*s);
    return 0;
}