Question about C array initialization

I understand that the statement
char string[] = "chars";
initializes string[5] to 0 ('\000'). My question is does the statement
char *strings[] = { "string1", "string2", "string3" };
initialize strings[3] to (void *) 0, i.e. NULL? I can't find the answer to this question in the ansi standard. GCC seems to tack on a NULL pointer at the end (even with the -ansi and -pedantic-errors flags), which is really convenient for finding the boundary, but I'm not sure whether it's a GCC thing or an official C thing. I see where the standard talks about terminating char arrays initialized by a string literal with a null byte, but it doesn't talk about the analogous case with arrays of pointers.
Last edited by nbtrap (2012-06-25 03:18:20)

nbtrap wrote:
Not necessarily. A declaration like:
char arr[3] = "str";
doesn't get null-terminated.
It doesn't get null-terminated because you don't leave enough room in the array for the null character. "char arr[3]" can only contain 3 characters, the same way that "char arr[2] = "str" will only contain 2. The second example generates a warning whereas the first does not, but only because it is very common to work with non-null-terminated strings.
nbtrap wrote:
And besides, my point is that initializing strings[3] *would* make sense for the same reason that intializing
char foo[] = "bar";
with a terminating null byte *does* make sense.
I know that arrays of pointers are not the same. My questions assumes that much. The fact of the matter is, however, GCC terminates pointer arrays of unknown size with a null pointer, and my question is simply "is this an ansi C thing or a GCC thing?".
In fact, it seems that GCC terminates all arrays of unknown size that are explicitly initialized with the appropriate number of null bytes. For example:
struct tag { int i; char c; char *str; } tags[] = {
{ 1, 'a', "string1" },
{ 2, 'b', "string2" },
{ 3, 'c', "string3" }
initializes tags[3] to sizeof (struct tag) null bytes. Try it for yourself.
I get the following:
test.c
#include <stdio.h>
int
main(int argc, char * * argv)
int i;
char *strings[] = { "string1", NULL, "string3"};
for (i=0;i<5;i++)
printf("strings[%d]: %s\n", i, strings[i]);
return 0;
output
strings[0]: string1
strings[1]: (null)
strings[2]: string3
Segmentation fault
test2.c
#include <stdio.h>
#include <string.h>
int
main(int argc, char * * argv)
int i;
struct tag {int i; char c; char *str;};
struct tag null;
memset(&null, 0, sizeof(struct tag));
struct tag tags[] =
{ 1, 'a', "string1" },
// { 2, 'b', "string2" },
null,
{ 3, 'c', "string3" }
for (i=0;i<5;i++)
printf(
"tags[%d]: (%p) %1d %c %s\n",
i, tags + i, tags[i].i, tags[i].c, tags[i].str
return 0;
output
tags[0]: (0x7fffd2df4e80) 1 a string1
tags[1]: (0x7fffd2df4e90) 0 (null)
tags[2]: (0x7fffd2df4ea0) 3 c string3
tags[3]: (0x7fffd2df4eb0) 0 (null)
Segmentation fault
The above behavior appears to conflict.
Given that string constants in C are defined as null-terminated, i.e. "str" is equivalent to "{'s', 't', 'r', '\0'}", the assignment 'arr[] = "str"' explicitly includes a null terminator. The other examples above do not include such a terminator. Even if it would be convenient sometimes, the standard should adopt a minimally invasive approach. It's easy to add a NULL at the end of an array declaration, but impossible to remove an extra element from such a declaration.
This may be informative too:
test3.c
#include <stdio.h>
#include <string.h>
int
main(int argc, char * * argv)
char str[] = "test";
char *strings[] = {"string1", NULL, "string3"};
struct tag {int i; char c; char *str;};
struct tag null;
memset(&null, 0, sizeof(struct tag));
struct tag tags[] =
{ 1, 'a', "string1" },
// { 2, 'b', "string2" },
null,
{ 3, 'c', "string3" }
printf(
"str\n size: %lu\n length: %lu\n"
"strings\n size: %lu\n length: %lu\n"
"tags\n size: %lu\n length: %lu\n",
sizeof(str), sizeof(str)/sizeof(char),
sizeof(strings), sizeof(strings)/sizeof(char *),
sizeof(tags), sizeof(tags)/sizeof(struct tag)
return 0;
output
str
size: 5
length: 5
strings
size: 24
length: 3
tags
size: 48
length: 3
The string length (actual number of chars in array) is reported as 5 ('t', 'e', 's', 't', '\0'), which is expected. The array of strings and tags are both reported as 3, even though you can access a null value after the last initialized index of the tags array. If that null value was really supposed to be there, it should be accounted for using sizeof, just as the null character is in the string.
Maybe the ultimate null element of the tags array is some artefact of memory alignment.

Similar Messages

  • About dynamic array initialization

    hi
    i read the matrix elements and its number in a main class,i initialize the matrix and print the matrix in a different class ,i have given the class that performs the initialize and printing,i have a error stating null pointer... in printmatrix method,i want to know what is the right way of initializing an array
    class matrix{
    public int num;
    public int arr[][];
    //=new int[3][3];
    public matrix(int number)
    num=number;
    public void addElements(int a1 [][])
    // public int arr[][];
    int arr[][] = new int[num][num];
    int i,j;
    for(i=0;i<num;i++){
    for(j=0;j<num;j++){
    arr[i][j]=a1[i][j];
    public matrix addMatrix(matrix aa)
    matrix c = new matrix(num);
    return c;
    public void printMatrix()
    int i,j;
    for(i=0;i<num;i++){
    for(j=0;j<num;j++){
    System.out.print(arr[i][j]);
    System.out.println("");
    System.out.println("");
    thanx

    Initializing an Aray:
    Object[] objects = new Object[42];
    Note that you now have 42 references still pointing to nothing. You just created an array. No objects for them.

  • Question about using arrays

    I have a web page written with combination of Front Page and Java is included. I have 4 drop down boxes which work in sequence. select an item in the first, it then asks you to select in the second box, then 3rd then in the final 4th box. This was set up using arrays. My question is how can i put a hyperlink to the items in the last drop down box? I want the last selection to go to a URL. can you tell me what code i need to use and where to insert it? I assume it has to go into the array somewhere. Thanks, Tom

    selection to go to a URL. can you tell me what code
    i need to use and where to insert it? Not without you clarifying your question and showing the relevant bits of your code, and possibly not even then.
    When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    I assume it
    has to go into the array somewhere. I assume it doesn't, because code doesn't go into arrays.

  • Question about sorting arrays

    Hi,
    I have posted information from an one-dimensional array on to a list widget. When a user selects an item in the list(index value = 3), presses the delete button, the item would be removed. Likewise, the element of the array at index value 3 would also be removed (or set to null?).
    The trouble I am having is, how would you move up the elements that are subsequent to the element index value 3? For example, moving element index value 4 up to 3, 5 up to 4, 6 up to 5....etc.?
    Here is my code:
    public void delete()
    list.delItem(list.getSelectedIndex());
    student[list.getSelectedIndex()]=null;
    Thanks alot!!

    It's usually faster to use System.arraycopy() to close up the "hole" when removing something from an array: public void delete() {
        int index = list.getSelectedIndex() ;
        list.delItem(index) ;
        // if not removing last item... close up hole...
        if (index < (student.length-1)) {
            System.arraycopy(student, index+1, student, index, student.length - 1 - index) ;
        // clear out space made empty at end of array
        student[student.length-1] = null ; // or whatever represents 'empty' in your student[]

  • Question about the Arrays utility

    Can I use the util.Arrays library to sort multi dimentional arrays? I dont see methods for that in the documentation, so I am guessing no.

    Yes it is. what kind of a comparetor would I need to set up for an int[][] array which I wish to sort in descending order according to the second dimension?
    Also, can you copy an array without using a for loop? I know that doing a = b (where a and b are both arrays of the same type) just passes a a referene to b.

  • Question about Java Array Primative Type.

    Say I create an Array of type Integer, like this:
    Integer [] myArray = new Integer[10];
    I now have an Integer array, 10 cells big.
    However, I have now learned that I can do the following:
    String [] [] [] stringArray = new String [3][3][3];
    I can create higher dimensional arrays!
    Is there any limit to the degree/dimension such an array may be,
    and does the Array class presently support any methods, like getDimension,
    to check the number of indices on an array where the number of indicies/dimensions
    are a priori unknown?

    And as far as I know, their is not limit to the depth of the arrays as long as you stay within the memory boundaries.In practice the depth is limited by the range of a Java 'int', because the array descriptor in the .class file is a String starting with the appropriate number of [ characters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Question about string array?

    Hello,
    When passing Stting arrays to a function, is there anyto test if the array is emply?
    void testFucntion(String[] test){
    }

    Or test the array is null.
    if (test == null || test.length == 0)

  • Question about an Array of objects

    I'm writing a program that is supposed to store a String and a double in an array of CustomerBill objects. I just want to know if I am doing it correctly. Heres my code:
    public static CustomerBill[] getCustomerData()
             //Local variables
             int numCust;     //The number of customers being processed
             double amt;
             String customer;        
          //Ask for the number of customers to be processed.
             System.out.print("How many customers are to be processed? ");
             numCust = Integer.parseInt(keyboard.nextLine());
             CustomerBill[] array = new CustomerBill[numCust];
             //Ask user to enter the data.
             System.out.println("\nPlease enter customer data when prompted.");
             System.out.println("Enter customer's last name, then first name.");
          //Get the customer data from user.
             for (int i = 0; i < array.length; i++)
               array[i] = new CustomerBill();
               System.out.print("\nCustomer name:  ");
               customer = keyboard.nextLine();       
               array.setName(customer);
    System.out.print("Total bill amount: ");
    amt = Double.parseDouble(keyboard.nextLine());
    array[i].setAmount(amt);
    System.out.println();
    return array;

    Write a test() method that:
    (1) Gets an array of CustomerBills using getCustomerData()
    (2) In a for-loop print out each of the CustomerBills. It will help if
    CustomerBill has a toString() method but, in any case you should be
    able to see that the aray contains the right number of nonnull elements.
    Then write a main() method that calls the test() method.
    [Edit] And then run it! You may need to do this a few times and check
    what happens with "crazy" data.

  • Question about nulling array elements

    Hi guys. What I want to do is null some array elements. Like:          
         for (int i = 1; i <= arrayA; i++) {
         for (int j = 1; j <= arrayB; j++) {
         Object o = class.getElem(i,j);
    o = null;
    Why this doesnt work? Thanks in advance

    You are only setting your local reference "o" to null. Whatever is in the class at index "i , j" is not affected--o is just a copy of the reference (not a copy of the object). You'll need something like:
    class.setElemNull(i,j);Where that method would set the appropriate value in your class to null.

  • Question about Object Arrays

    I am getting compile time error of missing ']' on the second line
        dvdData[] data = new dvdData[4];
        data[0] = new dvdData("Casablanca", "Warner Brothers", "1942");
        data[1] = new dvdData("Citizen Kane", "RKO Pictures", "1941");
        data[2] = new dvdData("Singin' in the Rain", "MGM", "1952");
        data[3] = new dvdData("The Wizard of Oz", "MGM", "1939");the object dvdData is being declared correctly with 3 strings as constructors, can anyone tell me why it is doing this? I will post complete code if nessecary.

    Hi,
    I don't see any problem - check out my code :-
    package project1;
    public class DVDData
        String str1 = null;
        String str2 = null;
        String str3 = null;
        public DVDData(String str1,String str2,String str3)
            this.str1=str1;
            this.str2=str2;
            this.str3=str3;
        public String toString()
            return str1 + " : " +    str2 + " : " + str3;
        public static void main(String[] args)
            DVDData[] data = new DVDData[4];
            data[0] = new DVDData("Casablanca", "Warner Brothers", "1942");
            data[1] = new DVDData("Citizen Kane", "RKO Pictures", "1941");
            data[2] = new DVDData("Singin' in the Rain", "MGM", "1952");
            data[3] = new DVDData("The Wizard of Oz", "MGM", "1939");
            System.out.println(data[0]);
            System.out.println(data[1]);
            System.out.println(data[2]);
            System.out.println(data[3]);
    }I get the correct output :-
    Casablanca : Warner Brothers : 1942
    Citizen Kane : RKO Pictures : 1941
    Singin' in the Rain : MGM : 1952
    The Wizard of Oz : MGM : 1939How are you comipling this ?
    Regards,
    Sandeep

  • Question about the programming of a legend

    Hello everybody,
    I have a question about the programming of a waveform's legend. I
    already asked here in this forum about the legend programming (03)
    months ago.
    I went satisfied but I ve just noticed that this code
    (See Code old_legend_test.llb with main.vi as main function) operates a
    little different from my expectances.
    Therefore I have a new question and I want to know if it
    is possible by labview programming to plot and show, on a waveform
    chart, a signal with activ plot superior to zero (0) without to be
    obliged to plot and show a signal with activ plot equal to zero (0) or
    inferior to the desired activ plot.
    I give you an example
    of what I m meaning. I have by example 4 signals (Signal 0, 1, 2 and 3)
    and each signal corresponds respectively to a channel (Chan1, Chan2,
    Chan3, Chan4). I want to control the legend (activ plot, plot name and
    plot color) programmatically. Is it possible with labview to plot signal
    1 or 2 or 3 or (1, 3) or (2,3) or (1,2,3) or other possible combination
    without to active the signal with the corresponding activ plot zero
    (0)?
    Let see the labview attached data
    (new_legend_test.llb with main.vi as main function). When I try to
    control the input selected values again I get them back but I don't
    understand why they have no effect on the legend of my waveform chart.
    Could somebody explain me what I m doing wrong or show me how to get a
    correct legend with desired plots? Thank by advance for your assistance.
    N.B.
    The
    both attached data are saved with labview 2009.
    Sincerly,PrinceJack
    Attachments:
    old_legend_test.llb ‏65 KB
    new_legend_test.llb ‏65 KB

    Hi
    princejack,
    Thanks for
    posting on National Instruments forum.
    The behavior
    you have is completely normal. You can control the number of row displayed in
    the legend and this rows are linked to the data you send to your graph. Thus,
    if you have 3 arrays of data, let say chan1, chan2 and chan3, you can choose
    which data you want to display in your graph using the property node (Active
    plot and visible). But for the legend as you send 3 plots there is an array of
    the plot name [chan1, chan2, chan3] and you can display 0, 1, 2 or 3 rows of
    this array but you cannot control the order in this array! So, to be able to
    change this array you have to only send data you need to you graph. I'm not
    sure my explanations are clear so I have implemented a simple example doing
    that.
    Benjamin R.
    R&D Software Development Manager
    http://www.fluigent.com/
    Attachments:
    GraphLegend.vi ‏85 KB

  • Questions About JSP?

    hi;
    I am php devloper and I am learning Java now.
    I am using NB6.1 , Tomcat 6.0 , J2ee 5.
    I have some questions about devleoping web application with jsp.
    1.What are
    /WEB-INF/web.xml
    /META-INF/context.xml
    /META-INF/MANIFEST.MF
    files that generated with NB.are important or optional.are auto generated or may I edit.
    2.can I distribute my web application in non text format.How?
    3.if I want to add some files to my application that its running in tomcat.how can i do that with out rebuild all.
    thank you
    Add to mtz1406's Reputation

    thank you all for helping.
    I will write more information about my questions may this help others:
    *{ /WEB-INF/web.xml* - The +Web Application Deployment
    Descriptor+ for your application. This is an XML file describing
    the servlets and other components that make up your application,
    along with any initialization parameters and container-managed
    security constraints that you want the server to enforce for you.
    This file is discussed in more detail in the following subsection.
    As mentioned above, the <code>/WEB-INF/web.xml</code> file contains the
    Web Application Deployment Descriptor for your application. As the filename
    extension implies, this file is an XML document, and defines everything about
    your application that a server needs to know (except the context path,
    which is assigned by the system administrator when the application is
    deployed).
    The complete syntax and semantics for the deployment descriptor is defined
    in Chapter 13 of the Servlet API Specification, version 2.3. Over time, it
    is expected that development tools will be provided that create and edit the
    deployment descriptor for you. In the meantime, to provide a starting point,
    a [basic web.xml file|http://localhost:8080/docs/appdev/web.xml.txt]
    is provided. This file includes comments that describe the purpose of each
    included element.
    NOTE - The Servlet Specification includes a Document
    Type Descriptor (DTD) for the web application deployment descriptor, and
    Tomcat 6 enforces the rules defined here when processing your application's
    <code>/WEB-INF/web.xml</code> file. In particular, you must
    enter your descriptor elements (such as <code><filter></code>,
    <code><servlet></code>, and <code><servlet-mapping></code> in
    the order defined by the DTD (see Section 13.3).
    h4. } from tomcat documentation
    Tomcat Context Descriptor
    bq. A /META-INF/context.xml file can be used to define Tomcat specific \\ configuration options, such as loggers, data sources, session manager \\ configuration and more. This XML file must contain one Context element, which \\ will be considered as if it was the child of the Host element corresponding \\ to the Host to which the The Tomcat configuration documentation contains \\ information on the Context element.
    }from tomcat documentation
    but I still want more information about this question:
    Q3: I want to distribute (sell to another organaization) without give sorce code in jsp files.So I want to precompile it to be just class files or jar files.
    I want to use ant that become with netbeans 6.1.can anyone give me information about how to do that.
    thank you again

  • Question about size of ints in Xcode

    Hello. I have a a few quick questions about declaring and defining variables and about their size and so forth. The book I'm reading at the moment, "Learn C on the Mac", says the following in reference to the difference between declaring and defining a variable:
    A variable declaration is any statement that specifies a variables name and type. The line *int myInt;* certainly does that. A variable definition is a declaration that causes memory to be allocated for the variable. Since the previous statement does cause memory to be allocated for myInt, it does qualify as a definition.
    I always thought a definition of a variable was a statement that assigned a value to a variable. If a basic declaration like "int myInt;" does allocate memory for the variable and therefore is a definition, can anyone give me an example of a declaration that does not allocate memory for the variable and therefore is not a definition?
    The book goes on, a page or so late, to say this:
    Since myInt was declared to be of type int, and since Xcode is currently set to use 4-byte ints, 4 bytes of memory were reserved for myInt. Since we haven't placed a value in those 4 bytes yet, they could contain any value at all. Some compilers place a value of 0 in a newly allocated variable, but others do not. The key is not to depend on a variable being preset to some specific value. If you want a variable to contain a specific value, assign the value to the variable yourself.
    First, I know that an int can be different sizes (either 4 bytes or 8 bytes, I think), but what does this depend on? I thought it depended on the compiler, but the above quote makes it sound like it depends on the IDE, Xcode. Which is it?
    Second, it said that Xcode is currently set to use 4-byte ints. Does this mean that there is a setting that the user can change to make ints a different size (like 8 bytes), or does it mean that the creators of Xcode currently have it set to use 4-byte ints?
    Third, for the part about some compilers giving a newly allocated variable a value of 0, does this apply to Xcode or any of its compilers? I assume not, but I wanted to check.
    Thanks for all the help, and have a great weekend!

    Tron55555 wrote:
    I always thought a definition of a variable was a statement that assigned a value to a variable. If a basic declaration like "int myInt;" does allocate memory for the variable and therefore is a definition, can anyone give me an example of a declaration that does not allocate memory for the variable and therefore is not a definition?
    I always like to think of a "declaration" to be something that makes no changes to the actual code, but just provides visibility so that compilation and/or linking will succeed. The "definition" allocates space.
    You can declare a function to establish it in the namespace for the compiler to find but the linker needs an actual definition somewhere to link against. With a variable, you could also declare a variable as "extern int myvar;". The actual definition "int myvar;" would be somewhere else.
    According to that book, both "extern int myvar;" and "int myvar;" are declarations, but only the latter is a definition. That is a valid way to look at it. Both statements 'delcare' something to the compiler, but on the second one 'define's some actual data.
    First, I know that an int can be different sizes (either 4 bytes or 8 bytes, I think), but what does this depend on? I thought it depended on the compiler, but the above quote makes it sound like it depends on the IDE, Xcode. Which is it?
    An "int" is supposed to be a processor's "native" size and the most efficient data type to use. A compiler may or may not be able to change that, depending on the target and the compiler. If a compiler supports that option and Xcode supports that compiler and that option, then Xcode can control it, via the compiler.
    Second, it said that Xcode is currently set to use 4-byte ints. Does this mean that there is a setting that the user can change to make ints a different size (like 8 bytes), or does it mean that the creators of Xcode currently have it set to use 4-byte ints?
    I think that "setting" is just not specifying any option to explicitly set the size. You can use "-m32" or "-m64" to control this, but I wouldn't recommend it. Let Xcode handle those low-level details.
    Third, for the part about some compilers giving a newly allocated variable a value of 0, does this apply to Xcode or any of its compilers? I assume not, but I wanted to check.
    I don't know for sure. Why would you ask? Are you thinking of including 45 lines of macro declarations 3 levels deep to initialize values based on whether or not a particular compiler/target supports automatic initialization? Xcode current supports GCC 3.3, GCC 4.0, GCC 4.2, LLVM GCC, CLang, and Intel's compiler for building PPC, i386, and x86_64 code in both debug and release, with a large number of optimization options. It doesn't matter what compiler you use or what it's behavior is - initialize your variables in C.

  • Question about navigation in session scope

    Hi.
    I dont know how to resolve a problem or how to focus this stuff.
    I'll try to explain myself.
    Let say I have a page (a.jsf) with several links, all this links navigates to the same page (b.jsf) which shows the results.
    For each link in a.jsf I have attached a bean with a logic, so If I click in link 1 I go to the b.jsf showing data read from the database.table1. If I clik in link2 I go to b.jsf showing data read from database.table2, and so on...
    The beans are in session scope (and must be).
    The first time works ok because I initialize the bean in b.jsf, read data and I show using a selecManyListBox to show it, but if I go back and select another link it goes to b.jsf, but it shows the old data, the data read the first time, because it never calls again the init method.
    Somebody has talked about using an additional bean to control this but once the bean in b.jsf is created I don't know how to call again the init method in beanB (b.jsf)..
    I have attached a very simple project to deploy in eclipse 3.3 and tomcat 6.0. In this example instead of read from database I read from an structure created in memory to simulate this.
    Somebody could take a look and comment something about it.
    http://rapidshare.com/files/197755305/_session-forms.war
    Thanks

    Hi.
    I understand is the same doing in the action method in a button or a commnad, the project is just an example, my real app is a tree, so is not a question about a button or a command, is about the logic being in session scope. I don't know how to face it.
    thanks

  • Question about IDashedAttributeValues interface

    Hi to everyone,<br />I have a question about IDashedAttributeValues interface.<br />If I would like to apply custom dashes kDashedAttributeValuesBoss to a page item. I would expect that my code will look like this:<br /><br />InterfacePtr<IDashedAttributeValues> pAttribute(::CreateObject(kDashedAttributeValuesBoss));<br /><br />pAttribute->SetPhase( nPhase );<br />pAttribute->SetCornerAdjustment((IDashedAttributeValues::CornerAdjustment)nCornerAdjust ment);<br />pAttribute->SetValue( 0, nDash0 );<br /><br />But InDesign crashes at SetValue code. I could understand InDesign. It is out of range. But, how to specify the length of value array or to add value into array?<br /><br />Thanks in advance,<br />Alexander Staroverov<br />Developer Engineer<br />Comosoft GmbH

    Thank you to all, I have found the answer in SDK samples:<br /><br />void SnpGraphicHelper::AddDashedValues(const K2Vector<PMReal>& dashAndGapValues)<br />{<br />IDataBase* db = fItemList.GetDataBase();<br />InterfacePtr<IDocument> theDocument(db, db->GetRootUID(), UseDefaultIID());<br />     InterfacePtr<IUIDData> uidData(::CreateObject2<IUIDData>(kDashedAttributeValuesBoss));<br />     ASSERT(uidData != nil);<br />     uidData->Set(::GetUIDRef(theDocument));<br />     InterfacePtr<IDashedAttributeValues> dashedAttributeValues(uidData, UseDefaultIID());<br />     if (dashedAttributeValues != nil && dashAndGapValues.size() > 0) {<br />          for (int32 i = 0; i < dashAndGapValues.size(); i++) {<br />               dashedAttributeValues->SetValue(i, dashAndGapValues[i]);<br />          }<br />          this->AddAnAttribute(dashedAttributeValues);<br />     }<br />}

Maybe you are looking for