首页 > 解决方案 > 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;
}

标签: cpointersdouble-pointer

解决方案


在您的第一个代码中,该q1 = NULL;行将零(null)值分配给指针,q1这是一个完全有效的操作(即使该指针可能指向另一个指针)。事实上,给NULL指针赋值是一种常见的技术,用于测试该指针当前是否包含有效地址(如果它是NULL,那么我们不能使用它)。

在您的第二个代码中*q1 = NULL;,您试图q1将零分配给由;指向的对象(本身就是一个指针) 。但是,q1尚未分配值(地址),因此它不指向任何有效目标,并且您的尝试失败(因为您正在尝试修改您可能没有的内存的“随机”部分进入)。


推荐阅读