简体   繁体   English

字符数组和指针的基本困惑

[英]character arrays and pointers basic confusion

I am a beginner in pointers. 我是指针的初学者。 after completing integer arrays and pointers i shifted to character arrays and pointers. 完成整数数组和指针后,我转向了字符数组和指针。 i expected the same results but its weird. 我期望相同的结果,但很奇怪。

int main() {    
    char chararray[20]="Char Array";      
    void printarray(char *);    
    void printarraydirect(char * );

    printf("Passing chararray to funtion printarray\n");    
    printarray(chararray);        
    printf("Printing directly as c in printarraydirect function");        
    printarraydirect(chararray);

     return 0;
}

void printarray(char *c){        
    int i=0;    
    //while(c[i]!= ' ')-----------------------> checks for empty space        
    while(c[i]!='\0')    
    {    
        printf("%c",c[i]);       
        i++;    
    }    
    printf("\n");    
}



void printarraydirect(char * c){        
    printf("Printing c-------------->");        
    printf("%s\n",c);        
    int i=0;        
    printf("Printing c[i]-------------->\n");
    // shows error here , if so why didnt it show me error in printarray function. and why didnt it print the whole array when printed c in printarray function..

    printf("%s\n" c[i]);

}

First of all, you're missing a comma on the line printf("%s\\n" c[i]); 首先,在行printf("%s\\n" c[i]);上缺少逗号printf("%s\\n" c[i]); . Secondly, c[i] is a single char (the element type of your array), hence the %s formatting is incorrect - it should be %c to print a single character. 其次, c[i]是单个char (数组的元素类型),因此%s格式不正确-打印单个字符应为%c Or if you wish to print the entire string from that point onwards, you need to pass the address of that element ( &c[i] ), but in this case that is the same as c since i is zero. 或者,如果您希望从该点开始打印整个字符串,则需要传递该元素的地址( &c[i] ),但是在这种情况下,由于i为零,因此它与c相同。

Basically %s format specifier expects an address to print to the output stream and it prints until it finds the NULL character( \\0 ). 基本上, %s格式说明符期望将地址打印到输出流,并打印直到找到NULL字符( \\0 )。 Here when you give simply c the base address of the array is passed as the argument. 在这里,当您简单地给出c ,将数组的基地址作为参数传递。 But when you give c[i] it is the value located at the location (base address + index) ie, addressOf(c) + valueOf(i). 但是当您给c[i]它是位于位置(基地址+索引)的值,即addressOf(c)+ valueOf(i)。

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

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