新手求教,C语言中指针作用是什么,为什么大部分人禁用goto?
自己编写程序中(刚刚学习,写的比较简单),感觉都没用到指针也没有,运用指针处理的习惯,但是据说C语言重点就是指针的运用,所以想请教一下什么地方要用指针。
[解决办法]
指针常用的地方:
1.字符串操作
2.在函数内部修改参数的值,不用指针就不可能
3.动态分配内存,就是用malloc构造的变量,是没有名字的,只能用指针访问
[解决办法]
指针访问快点,直接去它指定的地址去取值。Goto禁止是为了程序的安全。
[解决办法]
指针对于编程中的C语言
就象
突触对于大脑中的神经元。
goto对于C语言的程序结构
就象
连理枝对于现实中的森林。
[解决办法]
在c语言中,pointer和goto都是会被大量使用的东西
c没有destructor也没有垃圾回收,所以只能用goto模拟出一个
难以维护和使用的"destructor"
const int FilterScaleFactor = 2;
float *Input = NULL, *Filtered = NULL, *Output = NULL;
float *FilterRhoSamples = NULL, *RhoSamples = NULL;
int *BestStencil = NULL;
unsigned long StartTime0, StartTime;
int IntegerScaleFactor = (int)(Param.ScaleFactor + 0.5);
int InputWidth, InputHeight, OutputWidth, OutputHeight, OutputNumEl;
int i, Success = 1;
printf("Interp stencils... \t");
StartTime = Clock();
if(!(*SInterp = NewSInterp(StencilSet,
(float)Param.RhoSigmaTangent, (float)Param.RhoSigmaNormal)))
goto Catch;
printf("%7.3f s\n", (Clock() - StartTime)*0.001f);
if(!WriteImage(Output, OutputWidth, OutputHeight, Param.OutputFile,
IMAGEIO_FLOAT
[解决办法]
IMAGEIO_RGB, Param.JpegQuality)){
goto Catch;
}
//and so on
Success = 1;
Catch:
Free(Filtered);
Free(Output);
Free(BestStencil);
Free(Input);
Free(RhoSamples);
Free(FilterRhoSamples);
return Success;
你也许会问,这不是维护的地狱吗?当你有什么新的resource要回收的时候
不就得连Catch也一起修改?不过这就是c的套路,没有destructor和垃圾回收的下场
就是得大量的依赖goto
void swap(int &a, int &b)
{
int temp(a);
a = b;
b = temp;
}
更一般化的做法是
template<typename T>
void swap(T &&a, T &&b)
{
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}