Thread: pointers, structures, and strings

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2022
    Posts
    3

    pointers, structures, and strings

    Code:
    // This is just a basic description (representation) of what I'm trying
    // to do and what is happening.  I haven't programmed in C in a 
    // long time and I'm trying to refresh my skills.  I understand that 
    // things change and memory fails.  I'm using gcc 11.3 on a win10
    // machine.  This file should be fully compliable.
    
    
    #include <stdio.h>
    #include <string.h>
    
    
    struct x {
    char *y;
    };
    
    #define MAX 100
    struct x *z[MAX], *zz;
    
    
    int main ()
    {
    char a[100];
    int n=15;
    
    
    // I'm using fgetc to read one char at a time into a[] from a datafile
    // and parse as I go.
    
    
    // My "sample" input:
    a[0] = 'X'; a[1] = 'X'; a[2] = 'X'; a[3] = '\0';
    printf("a = %s\n",a);
    
    
    // So I use *zz to build the "local record" and this is where my
    // problem is:
    
    
    // Three main versions to do the same thing?? (only using one at
    // a time):
    //zz->y = &a[0];
    //*zz->y = a[0]; *(++zz->y) = a[1]; *(++zz->y) = a[2]; *(++zz->y) = a[3]; 
    strcpy(zz->y,&a[0]);
    
    
    printf("zz->y = %s\n",zz->y);  // This doesn't print because I believe
                                                 // the previous statements cause a
                                                 // segmentation fault and the run
                                                 // terminates.
    
    
    // When done with building the local record, I want to assign it to 
    // the next location in *z[]:
    z[n] = zz;
    printf("z[%i]->y = %s\n",n,z[n]->y);
    
    
    //I would also like to zero out *zz and a[] after every iteration.
    }
    // Where am I being slopy?  What changes are needed to make this
    // work?  I would prefer using strcpy.
    // -- Ravenhawk
    Last edited by Ravenhawk; 11-07-2022 at 04:06 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 04-02-2012, 07:38 PM
  2. C Strings in Structures.
    By SlyMaelstrom in forum C++ Programming
    Replies: 15
    Last Post: 10-12-2005, 04:29 PM
  3. Pointers to Classes || pointers to structures
    By C++Child in forum C++ Programming
    Replies: 24
    Last Post: 07-30-2004, 06:14 PM
  4. Strings and Structures
    By Kinasz in forum C Programming
    Replies: 3
    Last Post: 02-23-2003, 03:46 AM
  5. Replies: 5
    Last Post: 04-11-2002, 11:29 AM

Tags for this Thread