參考: http://www.jb51.net/article/42139.htm?_t=t 結構體類型數據作為函數參數(三種方法)
#include "stdafx.h"
#include"stdio.h"
void swap1(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
void swap2(int *x, int *y)
{
int *temp;
temp = x;
x = y;
y = temp;
}
void swap3(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void swap4(int a[], int b[])
{
int temp;
temp = a[0];
a[0] = b[0];
b[0] = temp;
}
void swap5(int a[], int b[])
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swap6(int *a, int *b)
{
if (*a != *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
}
void main(void)
{
int x = 4;
int y = 3;
swap1(x,y);
PRintf("swap1:x:%d,y:%d/r/n",x,y);
swap2(&x,&y);
printf("swap2:x:%d,y:%d/r/n", x, y);
swap3(&x, &y);
printf("swap3:x:%d,y:%d/r/n", x, y);
swap4(&x, &y);
printf("swap4:x:%d,y:%d/r/n", x, y);
swap5(&x, &y);
printf("swap5:x:%d,y:%d/r/n", x, y);
swap6(&x, &y);
printf("swap6:x:%d,y:%d/r/n", x, y);
getchar();
}

voidoxx(char*dest){ dest=(char*)malloc(30); strcpy(dest,"contenthasbeenmodied");}voidoxx2(char*dest){ strcpy(dest,"contenthatbeenmodied");}intmain(intargc,char*argv[]){ QCoreapplicationa(argc,argv); char* dest; char str[30]; dest=&str[0]; strcpy(dest,"It'sasimple"); oxx(dest); printf("oxxdest=%s/n",dest); oxx2(dest); printf("oxx2dest=%s/n",dest); getchar(); returna.exec();} 結論: [不要用return語句返回指向“棧內存”的指針,因為該內存在函數結束時自動消亡]

一個由C/C++編譯的程序占用的內存分為以下幾個部分: 1、棧區(stack)— 由編譯器自動分配釋放 ,存放函數的參數值,局部變量的值等。其 操作方式類似于數據結構中的棧。 2、堆區(heap) — 一般由程序員分配釋放, 若程序員不釋放,程序結束時可能由OS回 收 。注意它與數據結構中的堆是兩回事,分配方式倒是類似于鏈表,呵呵。 3、全局區(靜態區)(static)—,全局變量和靜態變量的存儲是放在一塊的,初始化的 全局變量和靜態變量在一塊區域, 未初始化的全局變量和未初始化的靜態變量在相鄰的另 一塊區域。 - 程序結束后由系統釋放。 4、文字常量區 —常量字符串就是放在這里的。 程序結束后由系統釋放 5、程序代碼區—存放函數體的二進制代碼。
int a = 0; 全局初始化區
char *p1; 全局未初始化區
main()
{
int b; //棧
char s[] = "abc"; //棧
char *p2; //棧
char *p3 = "123456"; //123456/0在常量區,p3在棧上。
static int c =0; //全局(靜態)初始化區
p1 = (char *)malloc(10);
p2 = (char *)malloc(20); //分配得來得10和20字節的區域就在堆區。
strcpy(p1, "123456"); //123456/0放在常量區,編譯器可能會將它與p3所指向的"123456"優化成一個地方。
//在strcpy執行的時候,會為生成一個p1的副本 char* _p1,在棧中
}
也就是說&s[0]、&b、&*p2、&*p3是不能用return來放回給調用者的,p1,p2,p3的值,即,靜態區內存和堆區去內存的地址都是可以返回的。
新聞熱點
疑難解答