Methodology Question: Initializing Static Arrays

After almost gnawing my arm off in frustration, I finally stumbled onto how to go about initializing and populating a static array that's outside of my Class's constructor (by placing it inside of a static block). My problem is, I just don't understand why I needed to do it that way. My code started out as such:
public class Parameter {
     private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
     appEnvironment[0].setMachineIP("192.168.1.100")
}and this kept throwing an error " ']' expected at line ###"
so I changed it to this:
public class Parameter {
     private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
     static {
     appEnvironment[0].setMachineIP("192.168.1.100")
}and it worked. Now my problem is, I'm assigning a literal, and I declared the Bean array as static, so the way I see it, there was no reason to throw assignments to the array inside of a static block. I'll take it as a "That's just the way it is" thing, but if someone out there could explain the reasoning behind having to put my assignments inside of a static block, it would really be appreciated.
Thanks!

Because if you didn't put it inside a static block you'd be attempting to execute code outside of a method which is illegal except for initialization.
I think you could do it this way:
private static appEnvironmentBean[] appEnvironment = {
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100"),
  new appEnvironmentBean().setMachineIP("192.168.1.100") };it depends on whether setMachineIP returns an appEnvironmentBean.

Similar Messages

  • Memory allocation when using multiple instances of a static array.

    Hi,
    I have question regarding the amount of memory allocated using multiple instances of a class that has declared a static array, e.g.:
    package staticTest;
    import javacard.framework.*;
    public class StaticClass
         static byte[] staticArray;
         public StaticClass()
              staticArray = new byte[100];
    /* Another class */
    package statictest;
    import javacard.framework.*;
    public class MyApplet extends javacard.framework.Applet
         StaticClass staticLibA, staticLibB;
         public MyApplet()
              /* Here we use two instances */
              staticLibA = new StaticClass();          
              staticLibB = new StaticClass();
         public static void install(byte[] bArray, short bOffset, byte bLength)
              (new MyApplet()).register(bArray, (short)(bOffset + 1), bArray[bOffset]);
         public void process(APDU apdu)
              byte[] buf = apdu.getBuffer();
              switch(buf[ISO7816.OFFSET_INS])
    }When downloading and installing this applet on a gemXpresso 211 PKis (that has a ' Get free EEPROM memory' function) the card reports that the amount of memory is increased by a approx 100 bytes every time a new staticLibX is added in the MyApplet constructor. Is this correct? If yes, can someone explain to me how to declare a static array that only allocates memory once and are being shared by the instances.
    Best regards,
    Jonas N

    Hi!
    I have another issue about static variable. The following is my sample code:
    ========================================
    package com.Test01;
    import javacard.framework.*;
    import javacard.security.*;
    import javacardx.crypto.Cipher;
    public class Test01 extends Applet {
         OwnerPIN Pin;
         static DESKey[] keys;
    protected Test01(byte[] buffer, short offset, byte length) {     
    keys = new DESKey[4];
    length = 0;
    while (length < 4) {
         keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);
         length = (byte)(length + 1);
    public static void install(byte buffer[], short offset, byte length) {     
    new Test01(buffer, offset, length);
    ===========================================================
    If there are two instances, A and B, created in the package.
    My issue:
    1. Are keys[0]~ keys [3] kept while B is deleted?
    2. Does each instance have itsown object while "keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);"?
    3. follow item 2, if A and B share the same object, is the object kept while B is deleted?
    Thank you
    Best regards,
    kantie

  • Initializing object array

    Hi,
    I am having problem initializing object array - here is my scenario -
    I have created class a -
    public class A {
    Public String a1;
    Public String a2;
    Public String a3;
    }the I have created class b
    public class B {
    Public A [] aa;
    }and I want to initialiaze my class bi in anoither clas c
    public class C{
    A ar = new A;
    ar.aa[0].a1 = "test"
    }this gives me null ..please anybody help me
    Neha
    }

    Thanks for the reply ..I know this is not good code ..but I have to write the classes in this way in SAP to create the Webservice ...the SAP side understand this type of structure only ..I still got the same error ..here are my original classes -
    public class GRDataItem {
         public String AUFNR ;
         public String EXIDP ;
         public String EXIDC;
         public String MATNR ;
         public String WERKS ;
         public String CHARG ;
         public String VEMNG ;
         public String VEMEH ;
         public String CWMVEMEH ;
         public String CWMVEMNG ;
         public String STATUS;
    public class GRDataTab {
         public GRDataItem [] grItem;
    Public class webservice {
                int sn = 20 ;
                  GRDataTab tab = new GRDataTab();
                tab.grItem = new GRDataItem[sn];
                tab.grItem[1].AUFNR = "12";
    }Thanks for all your help
    Neha

  • Accessing a Static Array in one CAP file from another CAP in same project

    Hi all,
    I have been developing a banking application on JavaCard. So the size of the applet has grown size able and have now split the file to multiple CAP files. I have been using NXP JCOP plugin in Eclipse for development. Below are the steps done
    a.) I have created multiple packages under the same project where one project has all the variable which are public static final and don't reference any other class. Also this package does not extend Applet. So it finally generates to a CAP file.
    b.) Another package which imports the above package and also extend Applet is the one which has all the UI and logic related to the project. The applet uses the static array defined in the another package to show the menu on phone.
    Now the problem is that when the code come to point for fetching the menu data, i have some thing like menu.length . But when the code comes to this point in debugger i get a
    +6F 00    Status: No precise diagnosis.+
    To cross check i put a watch on the menu variable and found that it has all the data required for showing the menu (which is of 32 byes). So now i am perplexed on why this length is giving this problem. Am i doing some thing wrong. Below is the Snip of the larger code
    This code is the package which has all the constants..
    package constantsPack;
    import javacard.framework.APDU;
    import javacard.framework.ISO7816;
    import javacard.framework.JCSystem;
    import javacard.framework.Util;
    public class ConstantsApplet {
    //menu array decleration
    public static final byte[] MAIN_SETUP_MENU = {
                       (byte) 0x81,  ConstantsApplet.CMD_DTL_LENGTH, ConstantsApplet.CMD_NUMBER, ConstantsApplet.MAIN_CMD_SET_UP_MENU, (byte) 0x00,
                       (byte) 0x82, (byte) 0x02, ConstantsApplet.DEVICEID_SIM, ConstantsApplet.DEVICEID_ME,
                       (byte) 0x85, (byte) 0x08 ,'A','B', 'C',' ','A','p','p','s',
                       (byte) 0x8F, (byte) 0x0D, ConstantsApplet.SB_MENU, 'A','b','c','d','e','f','g',' ','B','a','n','k',
    // other constants.
    }This is the package which has the applet and which uses the variables of the above package
    package myPkgLib;
    import constantsPack.*;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    import javacard.framework.OwnerPIN;
    import javacard.framework.Util;
    import javacard.framework.JCSystem;
    public class myApplet extends Applet{
    // other code
    fetch(ConstantsApplet.MAIN_SETUP_MENU.length);
    }Any help regarding this would be very helpful...
    Regards
    Prakash
    Edited by: prakash on Apr 18, 2012 11:57 PM

    Hi lexdabear,
    I tried putting a function inside the library package where the static array is present, but the results are the same... Also by try catch . what exception you want to catch... i see Exception has just .equal function... Tried with ExternalException also but does not seem to enter it..
    Attaching the source code compilable in eclipse below ..
    package constantsPack;
    public class ConstantsApplet {
         public static final byte[] MAIN_SETUP_MENU = {
              (byte) 0x81, (byte) 0x03, (byte) 0x01, (byte) 0x25, (byte) 0x00,
              (byte) 0x82, (byte) 0x02, (byte) 0x81, (byte) 0x82,
              (byte) 0x85, (byte) 0x08 ,'A','B', 'C',' ','A','p','p','s',
              (byte) 0x8F, (byte) 0x0D,  0x0F, 't','e','s','t','a','p','p',' ','B','a','n','k',
              public ConstantsApplet ()
    }The applet code where the above static array is used..
    package smilePkgLib;
    import constantsPack.*;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISOException;
    import javacard.framework.Util;
    public class BLApplet extends Applet{
         short fetchcode =0;
         public static void install(byte[] bArray, short bOffset, byte bLength) {
              // GP-compliant JavaCard applet registration
              new smilePkgLib.BLApplet().register(bArray,
                        (short) (bOffset + 1), bArray[bOffset]);
         private BLApplet(){
              // put init code
          * The main method.
         public void process(APDU apdu) throws ISOException {
              if (selectingApplet()) {
                   return;
              byte choosenMenuItem = 0;
              byte[] buf = apdu.getBuffer();
              byte bytesRead =(byte)(apdu.setIncomingAndReceive());
              fetchList(ConstantsApplet.MAIN_SETUP_MENU , (byte)0x00);
         private void fetchList(byte[] list, byte command){
              shouldFetch(list);
          * Overloaded method to fetch the MENUs only.     
          * @param menu
         private void shouldFetch(byte[] menu) {
              shouldFetch((byte)menu.length);
         private void shouldFetch(byte len) {
                   fetchcode = Util.makeShort((byte) 0x91, (byte) (len));          
    }The JCOP script to run the above project
    /select |DefaultApplet
    # Terminal Profile
    /send A0100000133B67FF7F1F020F0B4100000000869804000000 Have the eclipse loadable project but dont know how to put here...
    Regards
    prakash.

  • URGENT: Declaring Static Array after runtime

    Hi All
    Hope you can help me with this problem. I need to create a static array that can be used by other classes. I have declared the object in the beginning of the class, but I can only know the size after executing a method that is in that class.
    When I then try to create the object I get a NullPointerException when I run the program.
    THUS, how do I create a static array if I only know the size after the class is running?
    Hope you can help me
    COMLINK

    Are you suggesting that the following doesn't work for you?
    class MyClass{
        static String[] myStaticArray;
        public MyClass(){
        static void setArraySize(int size){
            myStaticArray = new String[size];
    }or are you trying to access the myStaticArray variable before you have set it to an actual array (i.e. using newString[size])?
    If the later, then you may need to use lazy initialization and access the array through a static getMyArray() function that tests for null, then populates the myStaticArray variable properly before returning it.
    - K

  • Initializing string array registers

    Hello. I have posted my project. It is not even close to finished but I am having trouble initializing the array's labeled "Up values" and "Down values", to "0" for all elements, at beginning of Vi run. So, when I am at the Front Panel and running the Vi, I would like all of the fields to begin with a "0", the moment the Vi is started. I have tried a couple different things I could think of and watched the Core 1 Video about arrays again however, it doesn't give the example for a string and nothing I have tried so far, is working. Thank you.

    crossrulz wrote:
    There are a few options to you:
    1. Use an initialization state to write to your indicators their default values via a local variable
    2. Put the default values into the indicators and then right-click on them and choose Data Operations->Make Current Value Default.  This will store the default value in the indicators themselves.
    I would recommend going with #1.
    2. Put the default values into the indicators and then right-click on them and choose Data Operations->Make Current Value Default.  This will store the default value in the indicators themselves. I put a "0" in each field, I slected "make current value default, but after the Vi ran, and then I started the Vi again, it keeps the numbers in the registers that are left over from the previous test. I also tried your suggestion #1. however, it still isn't writing a "0" in all the fields. The reason for this is that I don't want the operator's to read old data accidentally, when the Vi is running. I thought if I wipe all the registers out, it will prevent that from happening.

  • Questions about Static Initialiser Syntax

    Here is a simple script:
    public class Radio
    private int station;
    public Radio(int x)
    System.out.println("Constructing a Radio");
    station = x;
    static {
    System.out.println("Inside static initialiser");
    I was wondering how when you instantiate a radio object the Static initialiser method runs first before creating the radio. It is clear that it comes after Radio() in the script so how does the JVM know to jump to static and then back to Radio()?
    thanks
    Richard.

    A compiled java class contains two hidden methods, one called "<clinit>" which does the static intialisation and one called "<init>" which does the instance initialization. All the static initialisation which means any explicitly initialized static fields and static blocks are gatherered into the <clinit> method, in the order they are encountered. All the instance field initialisation (and any instance initializer blocks) are gathered into the <init> method (you'll sometimes see these names on stack traces).
    The first time you "actively use" a class <clinit> will be called first. When you instanciate a class the <init> method is called prior to any constructor code.

  • Initializing an array question

    if i wanted to initialize elements of an array and get input from the user of how many there will be. where can i find some info on this?
    basically instead of initializing 0,1,2,3, and so on i wanted to do it in a for loop, but i have tried it a couple of different ways with no luck.
    maybe you guys can give me some insight on how i need to set this thing up or what i need to think about or where some of the reading is?
    any info would help
    thanks in advance guys

    well here is the code for it i thought i was intializing it correctly??
    public static void main(String[] args) {
            int y;
            int x;
            int maxValue = 0;
            int numRepitions;
            int [] counters = new int[maxValue];
            Scanner keyin = new Scanner(System.in);
            Random generator = new Random();
                System.out.println("please enter how many random numbers you would like to generate");
                maxValue = keyin.nextInt();
                System.out.println("please eneter how many values your would like to draw for");
                numRepitions = keyin.nextInt();
                for(y = numRepitions - 1; y >= 0; y--)
                   counters[y] = numRepitions;
                   counters[numRepitions]--;
           

  • Best practice question - elipsis or array parameters?

    When I design APIs I have the choice between something like
        public static void foo(String[] params)
            // do stuff
        }or
        public static void foo(String... params)
            // do stuff
        }If I have both declarations I get the following error (which I can understand):
    "cannot declare both foo(java.lang.String...) and foo(java.lang.String[]) in blablabla.Main
    public static void foo(String... params)"
    So I can use one or the other. The question is: What is "better"?
    The elipsis version (with ...) looks nicer because I don't have to build an array prior to calling foo if my params do come from separate sources and I can pass them both separately.

    But isn't this the same as a call to foo(null) if I would have used the array version?Depends on how you implemented your method. Example:
    public static void foo1(String[] params) {
      for(String param: params) {
        System.out.println(param.length());
    public static void foo2(String... params) {
      for(String param: params) {
        System.out.println(param.length());
    public static void main(String[] args) {
      foo1(null);
      foo2();
    }The call foo1(null) would fail for obvious reasons, whereas foo2() would be valid.
    Lesson: an empty array is different from a null array.
    However, is there any other consideration I should do - performance for instance? Forget about performance: ellipsis is just a convenient way to overload a method for the no-arg case, so use it if you have a no arg-case, else use the array version.

  • 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.

  • Stalling a form from loading until the initial javascript arrays are loaded

    I am looking for a way to get a form to be hidden based on the onload event. I would like to call a javascript function to initially populate some select boxes based on javascript arrays, but I would like this to happen before the page loads or at least stall displaying the select boxes until they are populated.
    The way it is setup now, when the page loads, the select boxes try to load first and then the rest of the form loads. I would like to know if there is a way to load the select boxes from the javascript arrays, then have the select boxes and other form elements show up at the same time. I have tried putting a <div> around the entire form and within the javascript populate function I first use "document.formname.div_id.style.visibility=hidden" then at the end of the select box population within the function, I use "document.formname.div_id.style.visiblity=visible". I tried this and the select boxes appear blank; it is as if the populate function doesn't work at all.
    I realize this is a very long question, but I will award you Duke Dollars if you help me out!!!

    right now, I have it set up where I click on a link which is a jsp page which forwards me to the jsp page that has all the html in it. That page is where I initially try to populate the select boxes with the javscript arrays...I also have a number of javascript functions which change the contents of the select boxes based on another select box in the form. Will i have access to those "java" arrays, [instead of using the javascript arrays], that you are suggesting in the javascript code? I do need to use whatever arrays I create in javascript functions.

  • Administration Panel Error and a Question about Static IPs

    Since there appears to be no other place to report errors within the latest generation of Linksys router firmwares, I thought the forums may be the best place.
    If you use remote access to your router's Administration management console, upon saving any changes you are sent to the
    "Your settings have been successfully saved." page. Upon clicking cancel it successfully attempts to route to the appropriate hostname but does not consider the port being used; therefore, unless you have your management console hosted on port 80 it does not bring you back to the right place.
    This is mostly an annoyance.
    My question is I'm wondering if it's possible to assign static IP addresses from the router.
    On my older (much older) Linksys routers (before Cisco bought them out) you could easily assign static IPs.
    I cannot seem to find a way to do with newer generations.  All suggestions recommend assigning static IPs from the
    network devices themselves, however that poses problems on modern mobile devices which don't let you do that,
    and for laptops that are brought into a lot of different networks it becomes an annoyance to change those settings manually.
    I have a EA4500 router.
    Solved!
    Go to Solution.

    You want to assign a specific ip address to your computers/network devices thru the router? You can use the DHCP reservation feature of this router.
    "A DHCP Reservation is a permanent IP address assignment.  It is a specific IP address within a DHCP scope that is permanently reserved for leased use to a specific DHCP client."
    Please check this link:
    http://www6.nohold.net/Cisco2/ukp.aspx?vw=1&docid=71dac52653fa4944ae5e4f94ebdf9586_17362.xml&pid=80&...

  • Initializing an array of clusters in a CIN?

    I'm trying to write a CIN to connect to a mySQL database, retreive some information, and return it to labVIEW for display. The connection works perfectly using ODBC, but I'm having major trouble getting the information back to LabVIEW. I'm new to CINs and I'm still slightly confused as to how the different structures work. I want to return the data in an array of clusters (using struct names, a 'Set' of 'Records'). LV generated the structs, and I simply renamed some of the fields/names. The code I have so far works up to the point specified in the source below, when I try to initialize the array for data entry. I think what's throwing me off is the conplexity of my structures. Since it's an array of clusters, and not an array of say strings or integers, I'm getting confused. If anyone could help me out by telling me what's wrong with my code, and/or filling in the section of the while loop I'm rather clueless on.
    typedef struct {
    LStrHandle Number;
    LStrHandle SerialNumber;
    } Record;
    typedef struct {
    int32 dimSize;
    Record ptr[1];
    } Set;
    typedef Set **SetHdl;
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet);
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet)
    // LV error code
    MgErr err = noErr;
    // ODBC environment variables
    HENV env = NULL;
    HDBC dbc = NULL;
    HSTMT stmt = NULL;
    // Connection options data variables
    UCHAR* dsn = malloc(SQL_MAX_DSN_LENGTH * sizeof(UCHAR));
    UCHAR* user = malloc(32 * sizeof(UCHAR));
    UCHAR* pass = malloc(32 * sizeof(UCHAR));
    UCHAR* num = malloc(16 * sizeof(UCHAR));
    // Query variables
    INT qlen;
    INT nlen;
    UCHAR colNumber[5];
    SDWORD colNumberSize;
    UCHAR* query;
    INT numRows;
    // ODBC return code storage
    RETCODE retcode;
    /** Prepare data from LV for C++ manipulation **/
    strcpy(dsn, LStrBuf((LStrPtr)(*(ConnectionOptions->DSN))));
    dsn[(*(ConnectionOptions->DSN))->cnt] = '\0';
    strcpy(user, LStrBuf((LStrPtr)(*(ConnectionOptions->Username))));
    user[(*(ConnectionOptions->Username))->cnt] = '\0';
    strcpy(pass, LStrBuf((LStrPtr)(*(ConnectionOptions->Password))));
    pass[(*(ConnectionOptions->Password))->cnt] = '\0';
    strcpy(num, LStrBuf((LStrPtr)(*Number)));
    // Program crashes here too, but that's the least of my concerns right now. Keep reading down.
    //num[(**Number)->cnt] = '\0';
    qlen = (int)strlen(
    "SELECT m.Number FROM master AS m WHERE (m.Number LIKE '');"
    nlen = (int)strlen(num);
    query = malloc((qlen + nlen + 1) * sizeof(UCHAR));
    sprintf(query,
    "SELECT m.Number FROM master AS m WHERE (m.Number LIKE '%s'\0);",
    num);
    // Prepare and make connection to database
    SQLAllocEnv (&env);
    SQLAllocConnect(env, &dbc);
    retcode = SQLConnect(dbc, dsn, SQL_NTS, user, SQL_NTS, pass, SQL_NTS);
    // Test success of connection
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    retcode = SQLAllocStmt(dbc, stmt);
    retcode = SQLPrepare(stmt, query, sizeof(query));
    retcode = SQLExecute(stmt);
    SQLBindCol(stmt, 1, SQL_C_CHAR, colNumber, sizeof(colNumber), &colNumberSize);
    SQLRowCount(stmt, &numRows);
    //Program crashes on the following line. I get an error in LV saying something about an error in memory.cpp
    DSSetHandleSize((*RecordSet), sizeof(int32) + (numRows * sizeof(Record)));
    (**RecordSet)->dimSize = numRows;
    retcode = SQLFetch(stmt);
    numRows = 0;
    while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    /* Need code here to retreive/create Records and put them in the array */
    retcode = SQLFetch(stmt);
    numRows++;
    SQLDisconnect(dbc);
    else
    // Free ODBC environment variables
    SQLFreeConnect(dbc);
    SQLFreeEnv(env);
    // Return LV error code
    return err;

    This looks incorrect:
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet)
    Did you let LabVIEW generate the C file??
    When you pass an array of clusters to a CIN, what is passed is a handle to the array. You are declaring a pointer to a handle. I just did a test passing an array of clusters to a CIN. The C file looks like this (comments are mine):
    typedef struct {
    int32 Num1;
    int32 Num2;
    } TD2; // the cluster
    typeDef struct {
    int32 dimSize;
    TD2 Cluster[1];
    } TD1; // the array
    typeDef TD1 **TD1Hdl; // handle to the array
    CIN MgErr CINRun(TD1Hdl Array);
    Notice that it passes you a HANDLE, not a pointer to a handle.
    On this line:
    DSSetHandleSize((*RecordSet), sizeof(int32) + (numRows * sizeof(Record)));
    If RecordSet is a HANDLE, then (*RecordSet) is a POINTER - you are passing a POINTER to a routine that expects a HANDLE.
    The line:
    (**RecordSet)->dimSize = numRows;
    Is also incorrect - if RecordSet is a HANDLE, then (*RecordSet) is a POINTER, and (**RecordSet) is an ARRAY, but you're asking it to be a pointer. (*RecordSet)->dimSize would be the size to fetch.
    Read the rules again on what is passed to CINs.
    I strongly suggest developing the interface first - the VI that calls the CIN. Put the CIN in place and let LabVIEW generate the initial C file.
    Then modify the code to do something simple with the input arguments, like fetch the array size, and put this number into an output argument. Something VERY basic, just to test the ins and outs. Debug this until all ins and outs are working.
    THEN AND ONLY THEN add code to do whatever work needs doing.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Static array has to be static but cant be. AGH

    I'm completely stuck on this. I have two classes ChatClient and ChatClientListenThread. On ChatClient I have an enter button(enters text into chat) and an exit button(closes connection to server). I have to have the array as static, to pull it into actionPerformed. When I do that, it returns
    keysArray[0] = new Button("Enter");
    keysArray[1] = new Button("Exit");
    with NullPointerException: null. During run time.
    If there's a statement to make it.. not null which I think is the only way I can get this to work.
    If I don't have it static, In the actionPerformed It returns
    if(e.getSource() == ChatClient.keysArray)
    with non-static variable keysArray cannot be referenced from a static context.
    Here is all of my code for ChatClient, you'll need to set up just an empty class named ChatClientListenThread to get it to compile.
    import java.io.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    public class ChatClient extends Frame implements ActionListener
        public static  TextArea     chatArea;
        public         TextArea     nameArea;
        public         TextField    chatField;
        public         Button       enterButton;
        public         Button       exitButton;
        private static String       message;
        private        Panel        keyPanel;
        private static Button       keysArray[];
        public         boolean      foundkeySwitch;
        public         boolean      blankSwitch;
        public static  boolean      listenSwitch;
        static Socket                  s;
        static DataInputStream         user_in = null;
        static DataOutputStream        s_out   = null;
        static String                  stringToSend;
        static ChatClientListenThread  listeningThread;
        public ChatClient()
            chatField = new TextField(10);
            chatArea = new TextArea("Enter your name: \n", 10, 10);
            nameArea = new TextArea(10,15);       
            keysArray[0] = new Button("Enter");
            keysArray[1] = new Button("Exit");
            for(int i=0; i < keysArray.length; i++)
                keyPanel.add(keysArray);
    for(int i=0; i < keysArray.length; i++)
    keysArray[i].addActionListener(this);
    nameArea.setEditable(false);
    chatArea.setEditable(false);
    setLayout(new BorderLayout());
    add(chatArea, BorderLayout.CENTER);
    add(keyPanel, BorderLayout.EAST);
    add(chatField, BorderLayout.SOUTH);
    add(enterButton, BorderLayout.WEST);
    addWindowListener(
    new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    foundkeySwitch = (false);
    for (int i = 0; i < 2 && !foundkeySwitch; i++)
    if(e.getSource() == ChatClient.keysArray[i])
    foundkeySwitch = true;
    switch(i)
    case 0:
    try
    stringToSend = chatField.getText();
    s_out.writeUTF(stringToSend);
    stringToSend="";
    stringToSend = chatField.getText();
    chatField.setText("");
    chatField.requestFocus();
    s_out.writeUTF(stringToSend);
    chatField.setText("");
    chatField.requestFocus();
    catch (IOException ee)
    chatArea.setText("Error while writing : " + ee);
    break;
    case 1:
    listeningThread.stop();
    break;
    public static void main(String args[])
    ChatClient guiChat = new ChatClient();
    guiChat.setBounds(50,100,600,600);
    guiChat.setTitle("Chat");
    guiChat.setVisible(true);
    //Create a new socket
    try
    s = new Socket("localhost", 4554);
    s_out = new DataOutputStream( s.getOutputStream() );
    user_in = new DataInputStream( System.in );
    //Listening Thread
    listeningThread = new ChatClientListenThread(s);
    listeningThread.start();
    listenSwitch = (false);
    try
    //wait for listening
    Thread.currentThread().sleep(500);
    } catch (InterruptedException ee) { }
    catch (IOException ee)
    chatArea.setText("Error while writing : " + ee);
    //System.err.flush();

    move the code from the main method into the contructor.
    That should get rid of the "cannot access nonstatic variable from static context".
    Common problem - y don't you search the forum u ..^%^&%^$&!!!

  • Initializing an array

    I have an array that needs to be initialized 1096 times, I
    don't want to use a cfloop because I am looking for a better
    performance. So I use a query that brings all the records that have
    been initialized, the problem is if some of them hasn't been
    initialized and I use some conditionals as CFIF the application
    will throw an error because the specified position into the array
    doesn't exist yet.
    Here's my code.
    <cfquery name="lista_espacios"
    datasource="#Application.BD#">
    SELECT ISNULL(id_espacio,0) as id_espacio, ruta, url, alt
    FROM ESPACIOS
    ORDER BY id_espacio
    </cfquery>
    <cfloop query="lista_espacios">
    <cfset lista[lista_espacios.id_espacio][1] =
    lista_espacios.id_espacio>
    <cfset lista[lista_espacios.id_espacio][2] =
    lista_espacios.ruta>
    <cfset lista[lista_espacios.id_espacio][3] =
    lista_espacios.url>
    <cfset lista[lista_espacios.id_espacio][4] =
    lista_espacios.alt>
    </cfloop>
    <cfset cont=1>
    <cfif #lista[cont][1]# EQ #cont# ><a
    href="#lista[cont][3]#" onclick="abrirURL(#lista[cont][1]#);"
    target="_blank"><img style="border:0px" width="13"
    height="13" src="#lista[cont][2]#" title="#lista[cont][4]#"
    alt="#lista[cont][4]#" />
    </a>
    <cfelse>
    <img width="13" height="13" src="img/bad.jpg" />
    </cfif>
    <cfset cont = #cont#+1>

    quote:
    Originally posted by:
    Newsgroup User
    If I understand your requirements you have a database that
    has some
    records, but not necessarily all 1096 records at this time.
    You want to
    pull out these records, but have a full set of 1096 records
    even if some
    of them do not yet exist in the dataset.
    There are database tricks that can be used to create a record
    set like
    this. Hopefully somebody will chime in with the details. This
    would
    greatly simplify your processing after that.
    There is not enough information to know what approach would
    be most appropriate.
    What is the database type? Also, do the existing records have
    sequential values for idespacio, starting with 1?

Maybe you are looking for