c语言指针作为函数参数时候的注意事项怎样规避常见内存问题给几个典型的例子并纠正贴出完整可以运行的代码让我学习
注意事项:
-
指针作为函数参数时,需要注意指针的类型和指针所指向的数据类型是否一致。
-
函数内部对指针所指向的数据进行修改时,需要注意是否越界、是否已经被释放等问题。
-
在函数调用时,必须保证指针指向的数据已经被初始化。
例子1:
#include <stdio.h>
void change(int *p){
*p = 2;
}
int main(){
int *p;
change(p);
printf("%d",*p);
return 0;
}
该程序会出现段错误,原因是指针p没有被初始化,指向了一块不确定的内存地址,导致程序崩溃。正确的代码应该是:
#include <stdio.h>
void change(int *p){
*p = 2;
}
int main(){
int a = 1;
int *p = &a;
change(p);
printf("%d",*p);
return 0;
}
例子2:
#include <stdio.h>
void change(char *str){
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
}
int main(){
char str[5] = "1234";
change(str);
printf("%s",str);
return 0;
}
该程序会输出"Hello4",原因是在change函数中修改了str指针所指向的字符串,但是没有考虑字符串的长度,导致修改了后面的内存数据。正确的代码应该是:
#include <stdio.h>
#include <string.h>
void change(char *str){
strcpy(str,"Hello");
}
int main(){
char str[6] = "12345";
change(str);
printf("%s",str);
return 0;
}
例子3:
#include <stdio.h>
void change(int *p){
p++;
}
int main(){
int a[2] = {1,2};
int *p = a;
change(p);
printf("%d",*p);
return 0;
}
该程序会输出1,原因是在change函数中将指针p向后移动了一个int类型的存储空间,但是在函数外部的指针p并没有改变。正确的代码应该是:
#include <stdio.h>
void change(int **p){
(*p)++;
}
int main(){
int a[2] = {1,2};
int *p = a;
change(&p);
printf("%d",*p);
return 0;
}
完整代码:(以上三个例子的正确代码)
#include <stdio.h>
#include <string.h>
void change(int *p){
*p = 2;
}
int main(){
int a = 1;
int *p = &a;
change(p);
printf("%d\n",*p);
char str[6] = "12345";
change(str);
printf("%s\n",str);
int b[2] = {1,2};
int *q = b;
change(&q);
printf("%d\n",*q);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/fffd 著作权归作者所有。请勿转载和采集!