newbie question on strings & pointers

This is a discussion on newbie question on strings & pointers within the C Programming forums, part of the General Programming Boards category; How can I create a variable for storing a string of indeterminate length where a pointer won't work? eg, Code: ...

  1. #1
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    Angry newbie question on strings & pointers

    How can I create a variable for storing a string of indeterminate length where a pointer won't work? eg,
    Code:
    int main () {
         char *text;
         gets(text);
         puts(text);
    }
    will segfault. I'm asking because I want to read a file into one line with a loop, meaning this could be one very long line by the end. But string ops (strcpy, strcat) will not work with char pointers. Do I have to simply declare "text" as a gigantic array (char text[50000]) or is there a more dynamic means?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Short answer: You can't.

    Longer answer: Allocate the memory dynamically. Use a buffer to read, and store into a dynamic buffer. Consistently allocate more memory for the dynamic buffer until you read an entire line. Then use the dynamic buffer. This is a complicated approach.

    As for your statements that strcpy() and strcat() don't work with char pointers, you obviously are quite confused. They work perfectly fine with pointers. In your example with gets() (which shouldn't be used anyway), you have no memory allocated for your char *, so it points to some arbitrary memory location. gets() then attempts to trash wherever your char * points to. Not surprisingly, your OS slaps your program down to size and kills it for illegal memory access. You have to make your pointers point to valid locations. Pointers are just variables that contain addresses of other variables.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    what would a "dynamic buffer" be?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Memory returned from one of the *alloc() functions. You probably want realloc() for such a case.

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    Arrow alright

    I had my fingers crossed that "dynamic" meant something more "automatic", but anyway, for posterity's sake, here's what I worked out re: reading a file into one character array:
    Code:
    char *func (char *filename) {
         size_t len, tmem = 0;
         char *cumul, *line;
         FILE *fst = fopen(filename, "r");
         if (fst == NULL) puts("!!fopen failed!");
         while ((line = linein(fst)) != NULL) {
               len = strlen(line);
               if (mem = 0) {
                     mem = len+1;
                     cumul = (char *)malloc(mem);
                     strcpy(cumul,line);
               }
               else {
                     mem += len;
                     cumul = (char *)realloc(mem);
                     strcat(cumul,line);
               }
          }
          return cumul;
    }
    "linein" is another function but I think the point is clear...thanx all (ps. is there a simpler way at all??)
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Jul 2008
    Posts
    133
    Didn't test it, but it should work (but double-check it before usage

    Code:
    char *fReader(char *filename)
    {
        int size=0;
        char *str = NULL;
    
        FILE *f = fopen(filename, "r");
        if (!f) { puts("Idiot..."); return(NULL); }
    
        // make sure that even on empty file we return valid string (ends with zero):
        // (but if file ends with byte 0, we'll have 2 zeros in the end ;)
        // (EDIT: remove this line if you want function to return NULL on both fopen() fail AND
        // empty file)
        str = calloc(1,1);
    
        for (;;)
        {
            int c = fgetc(f);
            if (c == EOF) break;
    
            size++;
            str = realloc(str, size+1);
            str[size-1] = c;
            str[size] = 0;
        }
    
        fclose(f);
        return(str);
    }
    Last edited by rasta_freak; 08-05-2008 at 06:45 AM.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,021
    Quote Originally Posted by MK27 View Post
    I had my fingers crossed that "dynamic" meant something more "automatic", but anyway, for posterity's sake, here's what I worked out re: reading a file into one character array:
    Nope, sorry. It's the price you pay for working with such a low-level language as C.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. newbie question about strings
    By gp364481 in forum C Programming
    Replies: 11
    Last Post: 02-28-2009, 05:25 PM
  2. Newbie question (Pointers)
    By Tux_Fan in forum C Programming
    Replies: 21
    Last Post: 11-28-2008, 12:21 PM
  3. C++ newbie question about pointers
    By lafayette in forum C++ Programming
    Replies: 15
    Last Post: 09-30-2008, 01:38 PM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Pointers Question.....Null Pointers!!!!
    By incognito in forum C++ Programming
    Replies: 5
    Last Post: 12-28-2001, 11:13 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21