c - C中的指针和指向指针的指针
问题描述
嘿,我正在尝试理解指针,但我注意到在我的程序中导致未定义行为的某些东西在第一种情况下,当我将指向 q1 的指针衰减为 NULL 时,一切都很好,但是当我将指针 *q1 衰减为 NULL 时,终端不显示任何内容。出了什么问题?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *p[11]={"vasilis","loukas","vasilis","vasilis","giorgos","makis","vasilis","nikos","makis","nikos"};
char **p1;
char**d1;
char**q1;
q1=NULL;
p1=&p[0];
d1=&p[1];
/******Count words*********/
int count=0;
for(p1=&p[0] ; *p1 ; p1++)
{
count++;
}
printf("\nthe number of words : %d" ,count);
return 0;
}
第二种情况:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *p[11]={"vasilis","loukas","vasilis","vasilis","giorgos","makis","vasilis","nikos","makis","nikos"};
char **p1;
char**d1;
char**q1;
*q1=NULL;
p1=&p[0];
d1=&p[1];
/******Count words*********/
int count=0;
for(p1=&p[0] ; *p1 ; p1++)
{
count++;
}
printf("\nthe number of words : %d" ,count);
return 0;
}
解决方案
在您的第一个代码中,该q1 = NULL;
行将零(null)值分配给指针,q1
这是一个完全有效的操作(即使该指针可能指向另一个指针)。事实上,给NULL
指针赋值是一种常见的技术,用于测试该指针当前是否包含有效地址(如果它是NULL
,那么我们不能使用它)。
在您的第二个代码中*q1 = NULL;
,您试图q1
将零分配给由;指向的对象(本身就是一个指针) 。但是,q1
尚未分配值(地址),因此它不指向任何有效目标,并且您的尝试失败(因为您正在尝试修改您可能没有的内存的“随机”部分进入)。
推荐阅读
- typescript - 现在可以使用 Typescript 3.0 的通用休息参数来实现类型化的 zip 函数吗?
- reactjs - 在 MongoDB 中使用 React 捕获和存储地址
- python - 如何使用huey创建带有参数的任务函数?
- ios - AR资源图像有“警告”时ARKIT图像检测崩溃
- python - 在 matplotlib 中使用子图时获取空图
- java - 为什么我无法在 Play 商店中打开我的应用程序?
- twig - 社交元标签在 Pico CMS 2.0 中如何工作?
- android - Android Listview和Horizontalview - 如果单击图像,不知道如何获取图像文件名
- javascript - 使数组上的值匹配更快?
- javascript - 带有javascript函数的ATM机请求