What is the meaning of char *a[3]?

How can i understand the code char*a[3]? Does it mean declaring an array which can hold addresses of three characters?

#include <stdio.h>

    int main(void)
    {
        char *a;
        scanf("%s",a); 
        printf("%s \n",a);
        return 0;
    }

The above code does not work gives the output

(null)

I understand it is because the the declared pointer is pointing to nothing Then I ran the following code:

#include <stdio.h>

    int main(void)
    {
        char *a[1];
        scanf("%s",a[0]); 
        printf("%s \n", a[0]);
        return 0;
    }

This one works perfectly and can take indefinite amount of string length. Why is that?

2 answers

  • answered 2019-12-06 10:54 Blaze

    This one works perfectly and can take indefinite amount of string length. Why is that?

    Both of them are undefined behavior. It's just that undefined behavior isn't guaranteed to fail in any specific fashion, it can appear to work properly and then cause problems in different circumstances (which could include running the same program again on the same machine). On my machine, if I run this code, it crashes. The underlying issue is the same: a[0] is uninitialized and isn't pointing anywhere valid, just like a in the first program. Either way you'll have to allocate memory for the string that you're reading in:

    int main(void)
    {
        char *a[1];
        a[0] = malloc(20);
        scanf("%19s", a[0]);
        printf("%s \n", a[0]);
        free(a[0]);
        return 0;
    }
    

    Or without dynamical memory allocation:

    int main(void)
    {
        char a[20];
        scanf("%19s", a);
        printf("%s \n", a);
        return 0;
    }
    

    To answer the original question in the title: char*a[3] means "declare a as and array of 3 pointers to char".

  • answered 2019-12-06 11:01 ikegami

    What is the meaning of char *a[3]? Does it mean declaring an array which can hold addresses of three characters?

    Yes.

    It's an array that holds three pointers. The pointers must be of type char *, meaning they reference a char.

    char c1 = 'a';
    char c2 = 'b';
    char c3 = 'c';
    
    char *a[3] = { &c1, &c2, &c3 };
    
    printf("%c\n", *(a[0]));  // a
    

    The char referenced by these pointers could be part of an array of characters, as is the case when they point to a character of a string.

    char s1[] = "abc";
    char s2[] = "def";
    char s3[] = "ghi";
    
    char *a[3] = { s1, s2, s3 };
    
    printf("%s\n", a[0]);  // abc