博客
关于我
C指针-指针和数组
阅读量:345 次
发布时间:2019-03-04

本文共 1467 字,大约阅读时间需要 4 分钟。

指针的基本使用与常见问题

在C语言中,指针是内存访问的重要工具,但也伴随着潜在的危险。以下是一些关于指针的实例和常见问题的分析。

指针的初值赋予问题

C语言中的指针需要正确初始化,否则可能会导致程序运行错误。以下代码展示了一个常见的错误:

int main(void) {    int *p = 0;    *p = 12;    // *p未初始化时,可能指向内存中的不可写入区域    // 这会导致程序在运行时崩溃    return 0;}

在上述代码中,*p未被正确初始化,可能指向内存的不可写入区域。当尝试再次赋值时,程序会崩溃。因此,正确的做法是将指针初始化为有效的内存地址。

指针的交换操作

指针的交换可以通过简单的交换指针所指的内存地址来实现。以下代码展示了一个交换两个整数的指针:

void swap(int *a, int *b) {    int t = *b;    *b = *a;    *a = t;}

在主程序中:

int main() {    int a = 5, b = 6;    swap(&a, &b);    printf("a=%d, b=%d\n", a, b);    return 0;}

输出结果会显示a=6, b=5,证明指针成功交换了两个整数的值。

指针的结果存储

在C语言中,函数可以通过指针返回修改后的变量。在以下代码中,divide函数通过指针返回除法结果:

int divide(int a, int b, int *result) {    int ret = 1;    if (b == 0) {        ret = 0;    } else {        *result = a / b;    }    return ret;}

在主程序中:

int main(void) {    int a = 5, b = 2;    int c;    if (divide(a, b, &c)) {        printf("%d/%d=%d\n", a, b, c);    }    return 0;}

输出结果为5/2=2,表明函数正确地将结果存储在指针&c中。

指针的数组遍历

使用指针遍历数组时,需要注意数组的大小和内存的有效访问范围。以下代码展示了一个使用指针遍历数组的示例:

int main(void) {    int ai[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1};    int *p = ai;    while (*p != -1) {        printf("%d\n", *p++);    }}

输出结果会依次打印数组中的每个元素,直到遇到-1

多维数组的传递与操作

C语言支持多维数组的传递与操作。以下代码展示了一个使用多维数组的示例:

void m(int a[]) {    printf("%d\n", a);}void n(int *p) {    printf("%d\n", *p);}int main(void) {    int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};    int b[][2] = {{0, 0}, {1, 1}, {2, 2}, {3, 3}};    m(a);    n(a);    return 0;}

在运行时,m(a)会输出a数组的地址,而n(a)会输出a数组的第一个元素的值。

转载地址:http://zzde.baihongyu.com/

你可能感兴趣的文章
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node exporter完整版
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>