c - When doing `char first_word[MAX_LENGTH + 1] = "test";`, is first_word a pointer or a string? -


this question has answer here:

i have code:

char first_word[max_length + 1] = "test"; printf("word input: %s\n", first_word); printf("word input: %p\n", first_word); 

it prints both (prints string "test" , address).

in code, this:

char *arr_of_strings[max_length + 1]; arr_of_strings[0] = first_word; 

and sets arr_of_strings[0] whatever first_word (which in case pointer because *arr_of_strings array of pointers, right?). when do

printf("arr @ 0 is: %s\n", arr_of_strings[0]); 

it prints string again, can can print address so:

printf("arr @ 0 is: %p\n", arr_of_strings[0]); 

so when c use first_word string , when use pointer?

the correct answer an identifier array of characters.

  • it's not string, because string isn't type in c. string in c defined sequence of characters including 1 0 / '\0' character @ end (indicating end). so, first_word can hold string, can't is string. can hold sequence of char, not strings.

  • it's not pointer, although evaluates pointer in contexts. except when used sizeof, _alignof or &, identifier of array evaluated pointer it's first element. so, first_word have type char * (a pointer type) in many contexts, e.g. assign pointer char *foo = first_word. still, evaluating pointer doesn't mean is pointer. operators sizeof, _alignof , & evaluate different results when used on array vs. used on pointer.


regarding question printf: %s in printf requires pointer char (char *) passed , expects pointer point string. hope understand means after reading explanation above.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -