Struct, char array and pointer problem.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EARNEST
    New Member
    • Feb 2010
    • 128

    Struct, char array and pointer problem.

    Code:
    #include <string.h>
    #include <ncurses.h>
    #include <time.h>
    #include <stdlib.h>
    
    typedef struct builder{
    	int locX;
    	int locY;
    	char charValue_H;
    	char charValue_T;
    	char *charArray_B;
    } sbuilder;
    
    void drawborders();
    void initialize(sbuilder *stopass);
    bool collisiondetection();
    
    int main()
    {
    	initscr();
    	noecho();
    	cbreak();
    	sbuilder ss, *ptss;
    	ptss = NULL;
    	ptss = (sbuilder *) malloc (sizeof(sbuilder));
    	
    	initialize(ptss);
    	initialize(&ss);
    
    	mvprintw(10,10, "string is %s and %s", ss.charArray_B, ptss->charArray_B); //incorrect
        
        getch();
    	refresh();
    	endwin();
    	return 0;
    }
    
    void initialize(sbuilder *s)
    {	
    	//initial location
    	s->locY = LINES/2;
    	s->locX = COLS/2;
    	s->charValue_H = 'H';
    	s->charValue_T = 'T';
    
    	int i;
    	char s_initial[4];
    	
    	for (i = 0; i <= (sizeof(s_initial)-3); i++) //last loc  is /0
    	{
    		s_initial[i] = s->charValue_T;	
    	}
    	
    	s_initial[i] = s->charValue_H;
    
    	s->charArray_B = s_initial;
    	
    	mvprintw(1,1, "string is %s", s->charArray_B);  //correct
    }
    Correct output : TTH
    Incorrect: weird symbols
    Also, I wanted that function to return a struct, but i had similar problems.
    Any hints, please?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    In your initialize function you have s->charArray_B = s_initial. But s_initial is a local variable.

    You need to allocate this on the heap.

    I suggest a create function that a) creates your struct variable on the heap, b) calls initialize to initialize all the struct members and c) returns the addressof that struct variable. Then write a delete to free the struct variable

    In main():

    Code:
    sbuilder* ptr = Create();  //you could pass initial values as arguments
    
    //and you are set to go.
    
    //Finally, when you are done:
    
    delete(ptr);
    The Create() looks like:

    Code:
    sbuilder* Create()
    {
        sbuilder* temp = malloc(sizeof(sbuilder);
        Initialize(temp);
        return temp;
    }

    Comment

    • EARNEST
      New Member
      • Feb 2010
      • 128

      #3
      I managed (kinda) to solve it. Is it the right way?
      Code:
      	//initial location
      	s->locY = LINES/2;
      	s->locX = COLS/2;
      	s->charValue_H = '@';
      	s->charValue_T = '#';
      
      	int i;
      	char s_initial[4];
      	
      	for (i = 0; i <= (sizeof(s_initial)-3); i++)
      	{
      		s_initial[i] = s->charValue_T;	
      	}
      	s_initial[i] = s->charValue_H;
      	s->charArray_B = (char *)malloc((strlen(s_initial))*sizeof(char));	
      	strcat(s->charArray_B, s_initial);
      ?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        s_initial does not have a string in it. Even if it did, strlen would return a maximum of three.

        If it's 4 that you want, then code 4. If this is variable, then here's where I wouild use an argument for the Create() function:

        Code:
        sbuilder* Create(int arraysize)
        {
             sbuilder* temp = malloc(arraysize * sizeof(char));
             initialize(temp, arraysize);
             return temp;
        }
        This way the initialize funcition can just use the arraysize passed to allocate the array on the heap. You shouldn't need the local array at all.

        Comment

        • EARNEST
          New Member
          • Feb 2010
          • 128

          #5
          thanks, i used #define ARRAYSIZE 4;

          Comment

          • EARNEST
            New Member
            • Feb 2010
            • 128

            #6
            Should my initialize have (sbuilder *varpass) ?

            Comment

            • EARNEST
              New Member
              • Feb 2010
              • 128

              #7
              I have a problem. Cant figure out, any help, please:
              Code:
              #include <stdio.h>
              #include <stdlib.h>
              #include <ncurses.h>
              
              typedef struct testing
              {
              	int aa;
              	int bb;
              } loc;
              
              typedef struct useoftests
              {
              	char tchar;
              	loc *arrayoftests;
              }tester;
              
              tester *create_testcase();
              void init(tester *temper);
              
              int main()
              {
              	initscr();
              	tester *testerINST;
              
              	testerINST = create_testcase();
              	
              	refresh();
              	getch();
              	endwin();
              	return 0;
              }
              
              tester *create_testcase()
              {
              	tester *temptester;
              	temptester = malloc(sizeof(tester));
              	init(temptester);
              	return temptester;
              }
              
              void init(tester *temper)
              {
              	int ss;
              		
              	temper->arrayoftests = (loc *)malloc(15*sizeof(loc));	//malloc for body
              
              	ss = sizeof(temper->arrayoftests);
              	mvprintw(5,2, "size : %d", ss);
              }
              The output is 4 :/

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                arrayoftests is a pointer. The sizeof the pointer is 4.

                You cannot show the size of an array by using sizeof.

                sizeof shows the value of the variable on the stack. If you have a local array:

                Code:
                int array[6];
                and you sizeof(array) you will get 24 (65 integers at 4 bytes each).

                But if you pass the array to a function, what is passed is the address of element 0. Ahen you do a sizeof(array) inside the function you get 4, which is the sizeof the address of element 0.

                Likewise, when you create an array on the heap using the new operator or malloc what is returned is the address of element 0, which again is 4.

                Almost certainly you will need a separate variable for the number of elements.

                Comment

                • EARNEST
                  New Member
                  • Feb 2010
                  • 128

                  #9
                  Hm, you mean to get the size of an actual array in one function, and pass that variable to another function?

                  I am new to C, and I like it and very interested in it, but sometimes I think I want to break my screen :))))
                  Also, how come my string is not empty and it has weird symbols? How can i fix it? line 64, on ubuntu 9.10 everything is fine, however, freebsd 6.2 gives me weird symbols. cheers.
                  [code=c]
                  #include <string.h>
                  #include <ncurses.h>
                  #include <time.h>
                  #include <stdlib.h>


                  typedef struct foo
                  {
                  int var1;
                  int var2;
                  } foos;

                  typedef struct superfoo
                  {
                  int abc;
                  char *arrayofchars;
                  foos *yesfoos;
                  } superfoos;
                  superfoos *init_tester(in t ly, int lx);
                  void init_second(int y, int x, superfoos *temp);

                  int main()
                  {
                  initscr();

                  int locy;
                  int locx;

                  superfoos *beta;

                  locy = LINES/2;
                  locx = COLS/2;

                  beta = init_tester(loc y,locx);

                  mvprintw(20,20, "y:%d and x: %d", beta->yesfoos[0].var2, beta->yesfoos[1].var2-1);
                  mvprintw(5,5, "if true, head-1 is %d, head is %d", beta->yesfoos[0].var2, beta->yesfoos[1].var2-1);

                  getch();
                  refresh();
                  endwin();
                  return 0;
                  }
                  superfoos *init_tester(in t locy, int locx)
                  {
                  superfoos *temp;
                  temp = malloc(sizeof(f oos));
                  init_second(loc y, locx, temp);
                  return temp;
                  }

                  void init_second(int locy, int locx, superfoos *temp)
                  {
                  foos tempfoo[3];

                  tempfoo[1].var1 = locy;
                  tempfoo[1].var2 = locx;

                  tempfoo[0].var1 = locy;
                  tempfoo[0].var2 = --locx;
                  char *tempstring = "booboo";
                  temp->yesfoos = (foos *) malloc((sizeof( tempfoo)/sizeof(foos))*s izeof(foos));//malloc for body locations
                  temp->arrayofchars = (char *)malloc(strlen (tempstring)*si zeof(char));
                  mvprintw(10,15, "string before is %s%s", temp->arrayofchars," .");
                  memcpy(temp->yesfoos, tempfoo, sizeof(tempfoo) ); //assigning locations


                  }
                  [/code]

                  Comment

                  • weaknessforcats
                    Recognized Expert Expert
                    • Mar 2007
                    • 9214

                    #10
                    You seem to be going to a lot of toruble.

                    All you need do is a) allocate mempory and b) copy the data to that memory.

                    Note that oif your allocation is to contain a string then you need 1 additional byte to hold the \0 null terminator. Like this:


                    Code:
                    char* data = "Earnest";  /* the initial data */
                    
                    char array = malloc((strlen(data) +1)* sizeof(char));
                    strcpy(array, data);
                    strlen return the number of characters in a string,. In this case 7 since there are 7 characters in Earnest. Therefore, you need an 8 character array to told a 7 character string. Then just copy the data into your allocation.

                    It helps in C when working with strings to stick with the str... functions that are all set up to work with strings.

                    Comment

                    • EARNEST
                      New Member
                      • Feb 2010
                      • 128

                      #11
                      Hm, talking about pointers and th 0th location size. Is there a way to pass a struct that has lets say (int a, int b, struct structname2 *ssss) to another function and so that function would have access to all that data and store it to a shared memory segment, so other processes could read it? i've tried, but had problems with segmentation :(

                      Comment

                      • weaknessforcats
                        Recognized Expert Expert
                        • Mar 2007
                        • 9214

                        #12
                        You will need to read up on shared memory management for the operating system that you are using.

                        Keep in mind that pointer addresses are valid only from your process and you can't use those addresses in another process.

                        Comment

                        • EARNEST
                          New Member
                          • Feb 2010
                          • 128

                          #13
                          its ubuntu 9.10. trying to write a structure to a segment

                          Comment

                          • weaknessforcats
                            Recognized Expert Expert
                            • Mar 2007
                            • 9214

                            #14
                            Well, that's it for me. I don't know the first thing about ubuntu.

                            Comment

                            Working...