简体   繁体   English

指针和指向 C 中的指针的指针

[英]pointers & pointer to pointer in C

Hey I am trying to understand pointers and I noticed something which causes undefined behavior in my program In first case when I decay pointer to q1 to NULL everything is fine but when I decay pointer *q1 to NULL the terminal does not show anything.嘿,我正在尝试理解指针,但我注意到在我的程序中导致未定义行为的东西在第一种情况下,当我将指向 q1 的指针衰减到 NULL 时,一切都很好,但是当我将指针 *q1 衰减到 NULL 时,终端没有显示任何内容。 What is going wrong?出了什么问题?

#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;
}

second case:第二种情况:

#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;
}

In your first code, the q1 = NULL;在您的第一个代码中, q1 = NULL; line is assigning a zero (null) value to the pointer, q1 , which is a perfectly valid operation (even though that pointer potentially points to another pointer). line 正在为指针q1分配一个零(null)值,这是一个完全有效的操作(即使该指针可能指向另一个指针)。 In fact, assigning a NULL value to a pointer is a common technique, used so that code can test whether or not that pointer currently contains a valid address or not (if it's NULL , then we can't use it).实际上,将NULL值分配给指针是一种常用技术,用于测试该指针当前是否包含有效地址(如果它是NULL ,那么我们不能使用它)。

In your second code, *q1 = NULL;在您的第二个代码中, *q1 = NULL; , you are trying to assign zero to the object (itself a pointer) that is pointed-to by q1 ; ,您正在尝试将零分配给q1指向的 object (本身就是一个指针); however, q1 hasn't been assigned a value (an address), so it doesn't point to any valid target, and your attempt fails (because you are trying to modify a 'random' part of memory that you likely don't have access to).但是, q1尚未分配值(地址),因此它不指向任何有效目标,并且您的尝试失败(因为您正在尝试修改 memory 的“随机”部分,您可能不会可使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM