Does an array return a value?

Hello all!

My question:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>

int main()
{
	char ch[100]="A dog is running out!";

	int i;
	for(i=0; i<=20; i++){
		printf("%c",ch[i]);
	}
	printf("\n");

	//What is the situation of for()-loop ?
	for(i=0; ch[i]; i++){ //Does an array return a value? //What is that value?
		printf("%c",ch[i]);
	}
	printf("\n");

	return 0;
}


Output:
A dog is running out!
A dog is running out!


The 2nd for()-loop is working!
Last edited on
An array stores values of its type like a variable.

ch stores the memory address of the first element of the array.
ch[i] stores the value of the i element of the array.

In your code assuming i = 0, ch[i] is the first element of your array of char 'A'.

PS. Sorry for my bad english.
For C die-hard who like pointer so much iterating and print out values of an array can be done as well.

1
2
3
4
5
char *ptr = ch;
while (*ptr) {
  printf("%c", *ptr);
  ptr++;
}

Last edited on
Thank for your replies, naderST and sohguanh!

But I don't understand why the 2nd for()-loop is working.
C-strings (char arrays) end with a null character (literal value of zero). Since strings can be of any length, this is how the computer knows it has reached the end of the string.

1
2
3
for( ...; ch[i]; ... )  // <- this loop condition

for( ...; ch[i] != 0; ... )  // <- is a shorthand way to say this 


The null is put there automatically by the "double quotes":

1
2
3
4
5
char foo[20] = "foo";  // this

// is the same as this:
char foo[20] = { 'f', 'o', 'o', 0 };  // <- note it ends with a literal 0
 // that marks the end of the string 


The 2nd loop is simply looking for that end-of-string marker.
Thank you, Disch!

I know why the 2nd for()-loop is working now!
Topic archived. No new replies allowed.