Home > database >  Reading string in an array in C
Reading string in an array in C

Time:11-19

I'm new to C programming, and I wondered how it worked to read strings in an array. Here is the example that confuses me:

int main(void) {
    char array[100] = {'a', 'b', 'c', '\0'}; 
    // we add the '\0', so it doesn't read the entire array

    array[98] = 'x'; 
    // define that at index [98] there is character 'x'

    char *p, *q; 
    // creates pointers

    p = array; 
    // pointer p now points toward the address of the array, 
    // which is index [0]

    printf("%s", p); 
    // Will print everything until a '\0' is reached, 
    // so print 'abc'

    printf("%s", (p   2)); 
    // p is now pointing at the address of index[2], 
    // so print 'c'

    q = &array[5]; 
    // pass the address of index[5] to q

    printf("%s", q); 
    // what is printed out?
}

I thought that the last line printf("%s", q); would print everything in the array until it reaches a \0 because we specify %s in printf. So, the 'x' would be printed, but when I run the program, nothing gets printed. Why is that?

I get

abcc

Could you explain me step by step what happens when I read my program? (I'm a newbie)

CodePudding user response:

When you created your array, only the first 4 bytes were properly initialized. The rest of the array, so the other 96 bytes were initialized to 0, So when printing starting at index 5, it is being treated as an empty string

CodePudding user response:

At line number 2 I.e array[98]='x'; //define that at index [98] This is wrong declaration as well as initialization of character array.So this line will not work. For writing character array, the syntax is :--- data_type name[size]

printf("%s", p); //Will print everything until a '\0' is reached, so print 'abc'

printf("%s", (p 2)); //p is now pointing at the address of index[2], so print 'c' That's all remaining will not printed

  • Related