Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 29 July 2013

Arrays - C Interview Questions IV


Q. Why can't constant values be used to define an array's initial size?
There are times when constant values can be used and there are times when they can't. A C program can use what C considers to be constant expressions, but not everything C++ would accept.
When defining the size of an array, you need to use a constant expression. A constant expression will always have the same value, no matter what happens at runtime, and it's easy for the compiler to figure out what that value is. It might be a simple numeric literal:
char a[ 512 ];
Or it might be a "manifest constant" defined by the preprocessor:
#define MAX     512
/* ... */
char    a[ MAX ];
Or it might be a sizeof:
char a[ sizeof( struct cacheObject ) ];
Or it might be an expression built up of constant expressions:
char buf[ sizeof( struct cacheObject ) * MAX ];
Enumerations are allowed too.
An initialized const int variable is not a constant expression in C:
int max = 512; /* not a constant expression in C */
char buffer[ max ]; /* not valid C */
Using const ints as array sizes is perfectly legal in C++; it's even recommended. That puts a burden on C++ compilers (to keep track of the values of const int variables) that C compilers don't need to worry about. On the other hand, it frees C++ programs from using the C preprocessor quite so much.

Q. What is the difference between a string and an array?
An array is an array of anything. A string is a specific kind of an array with a well-known convention to determine its length.
There are two kinds of programming languages: those in which a string is just an array of characters, and those in which it's a special type. In C, a string is just an array of characters (type char), with one wrinkle: a C string always ends with a NUL character. The "value" of an array is the same as the address of (or a pointer to) the first element; so, frequently, a C string and a pointer to char are used to mean the same thing.
An array can be any length. If it's passed to a function, there's no way the function can tell how long the array is supposed to be, unless some convention is used. The convention for strings is NUL termination; the last character is an ASCII NUL ('\0') character.
In C, you can have a literal for an integer, such as the value of 42; for a character, such as the value of '*'; or for a floating-point number, such as the value of 4.2e1 for a float or double.
There's no such thing as a literal for an array of integers, or an arbitrary array of characters. It would be very hard to write a program without string literals, though, so C provides them. Remember, C strings conventionally end with aNUL character, so C string literals do as well. "six times nine" is 15 characters long (including the NUL terminator), not just the 14 characters you can see.
There's a little-known, but very useful, rule about string literals. If you have two or more string literals, one after the other, the compiler treats them as if they were one big string literal. There's only one terminating NUL character. That means that "Hello, " "world" is the same as "Hello, world", and that
char    message[] =
  "This is an extremely long prompt\n"
  "How long is it?\n"
  "It's so long,\n"
  "It wouldn't fit on one line\n";
When defining a string variable, you need to have either an array that's long enough or a pointer to some area that's long enough. Make sure that you leave room for the NUL terminator. The following example code has a problem:
char greeting[ 12 ];
strcpy( greeting, "Hello, world" );    /* trouble */
There's a problem because greeting has room for only 12 characters, and "Hello, world" is 13 characters long (including the terminating NUL character). The NUL character will be copied to someplace beyond the greeting array, probably trashing something else nearby in memory. On the other hand,
char greeting[ 12 ] = "Hello, world"; /* not a string */
is OK if you treat greeting as a char array, not a string. Because there wasn't room for the NUL terminator, the NUL is not part of greeting. A better way to do this is to write
char greeting[] = "Hello, world";
to make the compiler figure out how much room is needed for everything, including the terminating NUL character.
String literals are arrays of characters (type char), not arrays of constant characters (type const char). The ANSI C committee could have redefined them to be arrays of const char, but millions of lines of code would have screamed in terror and suddenly not compiled. The compiler won't stop you from trying to modify the contents of a string literal. You shouldn't do it, though. A compiler can choose to put string literals in some part of memory that can't be modified—in ROM, or somewhere the memory mapping registers will forbid writes. Even if string literals are someplace where they could be modified, the compiler can make them shared.
For example, if you write
char    *p = "message";
char    *q = "message";
p[ 4 ] = '\0';  /* p now points to "mess" */
(and the literals are modifiable), the compiler can take one of two actions. It can create two separate string constants, or it can create just one (that both p and q point to). Depending on what the compiler did, q might still be a message, or it might just be a mess.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...