malloc string array

This is a discussion on malloc string array within the C Programming forums, part of the General Programming Boards category; Hi. Im quite new to c programming. Im trying to figure out how to use malloc. I saw a question ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    10

    malloc string array

    Hi. Im quite new to c programming. Im trying to figure out how to use malloc. I saw a question similar to this in the forum but it was a good bit more complicated and I didnt really understand it.

    I want to create a 1D array of ints from a file. I had a stab at it but the while loop isnt correct, am going about it the right way?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    int main(void)
    {
    	FILE *fid;
    
    	int * iarray;
    	int n=0;
    	
    	fid = fopen("unsorted.txt", "r");									
    	if (fid == NULL)
            {
    		printf("Cannot open file\n");							
    		exit(EXIT_FAILURE);
    	}
    	
    	iarray = (int *) malloc ( n * sizeof(int) );
    
    	iarray[n] = fgets(fid);
    	while( ( iarray[n] = fgets(fid) ) != EOF )
    	/*or ?     while(fscanf(fid, "&#37;s", &iarray[n]) != EOF )*/
    	{
    	
    		fscanf(fid, "%d", &iarray[n]);
    		n++;
    	
    	}
    
    
    	
    
    
    	fclose(fid);
    	printf("%d", iarray[n]);
    	
    	return(0);
    }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    You are using it correctly however for every element that you add you must malloc() storage which is being invoked only once.
    n != 0 otherwise the call to malloc() will return a null pointer since you are essentially requesting no storage at all.
    Changes to be made to the source are in red.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    int main(void)
    {
    	FILE *fid;
    
    	int * iarray;
    	int n=0;        /* should not be initialized to zero */
    	
    	fid = fopen("unsorted.txt", "r");									
    	if (fid == NULL)
            {
    		printf("Cannot open file\n");							
    		exit(EXIT_FAILURE);
    	}
    	
    	iarray = (int *) malloc ( n * sizeof(int) ); /* goes inside while loop because you need to store each new array element added */
    
    	iarray[n] = fgets(fid);
    	while( ( iarray[n] = fgets(fid) ) != EOF )
    	/*or ?     while(fscanf(fid, "%s", &iarray[n]) != EOF )*/
    	{
    	
    		fscanf(fid, "%d", &iarray[n]);
    		n++;
    	
    	}
    
    
    	
    
    
    	fclose(fid);
    	printf("%d", iarray[n]);
    	
    	return(0);
    }

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    10
    Thanks for your help. The problem now is I am making a string array and comparing this to an int. I messed around a lot and came up with the following line:

    while( (a = atoi(fgets(iarray, 2, fid) )) != EOF )

    It compiled with no errors but when i tried to run the program I got error while dumping....Could you help me with this while statement please?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    What string array? You don't have a string array in your code anywhere. You have iarray, which is an array of integers that you are filling in an ... interesting way. You don't have a char array either.

    Maybe you should start by figuring out what the program is supposed to do. If you're supposed to read integers from a file, you don't use fgets (unless you're ultra paranoid).

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    10
    Ok.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    int main(void)
    {
    	FILE *fid;
    
    	int * iarray;
    	int n=0;
    	
    	fid = fopen("unsorted.txt", "r");								
    	if (fid == NULL)
           {
    		printf("Cannot open file\n");						
    		exit(EXIT_FAILURE);
    	}
    	
    	
    
    	while( (fscanf(fid, "&#37;d", &iarray[n]) != EOF ) ) 
    	{
    		iarray = (int *) malloc ( n * sizeof(int) );
    		/*fscanf(fid, "%d", &iarray[n]);*/
    		n++;
    	
    	}
    	
    
    	
    
    
    	fclose(fid);
    	printf("%d\n", iarray[0]);  prints the last number in the file
    	printf("%d\n", iarray[1]);  prints 0 ???
    	printf("%d\n", iarray[2]);  prints 0 ???
    	printf("%d\n", iarray[32]); prints 0 ???
    	printf("%d\n",n);               33 - there are 33 ints in the file
    	
    	return(0);
    }
    What I take out of this is that the malloc part isnt working. My array will only take in 1 value, and keeps replacing this value with a new value until it exits the loop. Is this because you cannot update the array size after you have declared it once?
    Last edited by Tayls; 10-24-2008 at 12:37 PM.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Each malloc gives you a new piece of memory, yes. If you want to resize the current piece of memory, you should use realloc.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,627
    I'm afraid itCbitC was a little off.
    You cannot use a pointer before you allocate some memory!
    The malloc should be before the loop and stored inside the pointer for the total number of elements you need. The formula is generally: n * sizeof(type), where n is the number of elements and type is the type of array.

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,305
    I believe you will want to use realloc in the loop.
    Note that at the moment you have a buffer overrun and a memory leak.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    10
    Now my printfs dont print anything

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    int main(void)
    {
    	FILE *fid;
    
    	int * iarray;
    	int n=0;
    	
    	fid = fopen("unsorted.txt", "r");		
    	if (fid == NULL)
           {
    		printf("Cannot open file\n");					
    		exit(EXIT_FAILURE);
    	}
    	
    	iarray = (int *) malloc ( (n+1) * sizeof(int) );
    
    	while( (fscanf(fid, "&#37;d", &iarray[n]) != EOF ) ) 
    	{	
    		iarray = realloc(iarray, (n+1)*sizeof (int));
    		n++;
    		
    		
    	
    	}
    	
    
    	
    
    
    	fclose(fid);
    	
    	printf("%d\n", iarray[0]);
    	printf("%d\n", iarray[1]);
    	printf("%d\n", iarray[2]);
    	printf("%d\n", iarray[32]);
    	printf("%d\n",n);
    
    	free(iarray);
    	return(0);
    }
    btw iMalc on your website I cant get your "best bubsort" to show source code
    Last edited by Tayls; 10-24-2008 at 03:24 PM.

  10. #10
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Once you free(iarray), it's gone (or could be gone, or may be gone -- we don't know, is the point). So you would have to printf before you free anything.

  11. #11
    Hacker MeTh0Dz's Avatar
    Join Date
    Oct 2008
    Posts
    111
    Why would you free an array then try to print it's members?

  12. #12
    Registered User
    Join Date
    Oct 2008
    Posts
    10
    Still doesnt print....

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Code:
    iarray = realloc(iarray, (n+1)*sizeof int);

  14. #14
    Registered User
    Join Date
    Oct 2008
    Posts
    10
    If i knew what was wrong with that line would it be there?

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The point is that is what the line should be -- you need n+1 ints, not n+1 bytes.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

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