![]() |
| ||
| Arrays and Pointers Hi. I recently read that using the name of an array without brackets was one method for accessing the <address> of the array's first element. E.g: #include <stdio.h>Thanks for the help, java_girl |
| ||
| Re: Arrays and Pointers You are right that the array name is the address of the first element of that array. This works exactly the same for arrays of char as well. In C, there is no "string" type, so we are forced to use arrays of char. There is one special difference between a string (array of char) and other arrays, and that is that the last element of a string MUST be the null terminating character '\0'. This signifies the end of the string. The puts() function will take a char*, assume it is a string ( an array of char), and output all the chars in the array up to the null terminating character. By using printf in the way you are using it, you are telling it to output one character (%c) and giving it the first character of the string (since you dereference the array, giving you the first element). If you want to print the whole string, use %s and don't dereference the array. You could also print any single character within a string by just giving the index of the character. For example: printf( "%c\n", message2[3] ); // this will print 't' |
| ||
| Re: Arrays and Pointers Some additions: 1. To print pointer value use %p (not %d) format specifier. As usually, it's a senseless operation ;). 2. True type of a string literal is const char*- a constant pointer to the 1st element of a char array contained a string with terminated null character. You can't change string literal via pointer to it. Constructs like char* message1 = "C";are valid (for backward compatibility with older C programs) but modern compilers place literals in read-only memory. 3. An array name is not converted to a pointer to the 1st element of an array (&array[0])in sizeof array_name(operator sizeof argument position). |
| ||
| Re: Arrays and Pointers if u want to print the address of first character in the string it is same as you did with other array. For Ex. int intArray[3] = {1,2,4};the job of puts(str) function is to print all the character starting at address str till it finds '\0'. |
| All times are GMT -4. The time now is 6:06 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC