Thread: strtol() / malloc

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    8

    strtol() / malloc

    ok im trying to sort a bunch of numbers from a file. the file is stated via argv[2] and i want to sort the first n numbers of the file. n is equal to argv[1].

    Whenever so the imput i have been using is ./a.out 5 testdata

    when th code is run its printing out just a new line. I know there nothing wrong with the printf statements and im pretty sure it has something to do with declaring my arrays.

    Here is my code

    I've basicly narrowed it down to either my strtol fuction or malloc. Im leaning toward malloc on accounts that im not 100% sure i know what is is im doing with that.

    Any help would be agreatly apreciated.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[]){
    
      int *value ;
    
      int num = strtol(argv[2], NULL, 10);
    
      int temp ;
    
      FILE *fin = NULL ;
    
      int i;
    
      int k;
    
      value = malloc( sizeof (num) * num);
    
      fin = fopen(argv[2],"r");
    
      for( i = 0; i <=num; i++){
        fscanf(fin, "%d", &value[i]);
      }
    
      for(k = 0; k < num; k++){
    
        if(value[k + 1] > value[k]){
    
          temp = value[k];
    
          value[k] = value[k+1];
    
          value[k+1] = temp;
         }
        else
          value[k] = value [k];
      }
    
        for(j = 0; j < num; j++){
        printf("%d", value[j]);
      }
    
      printf("\n");
    
      return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    int num = strtol(argv[2], NULL, 10);
    argv[1], perhaps?

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    8
    lol wow im dumb. still dont work but i can see numbers now to debug it. ty

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The lesson here is "when in doubt start printing things" -- you would have seen the 0 (or garbage) and known where to look.

    Edit: As to the other:
    Code:
    for( i = 0; i <=num; i++){
    Remember: red means stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 09:42 AM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM