Thread: Extending arvg[]

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    2

    Extending arvg[]

    My question is how can I extend my argv from inside main so that if a user provides file xx the progam behaves as if it provided two xx input files?


    example:

    Code:
    ./run xx
    
    // I have 
    
    argv[0] = ./run
    argv[1] = xx
    
    /but now I wish to have behaviour as if i have executed:
    
    ./run xx xx
    
    argv[0] = ./run
    argv[1] = xx
    argv[2] = xx

    any advice ??


    Code:
    int main (int argc, char*argv[]){
    
       char **p = argv;
        argc = 0;
        while (*p++ != NULL) {
            argc++;
        }
    
        for (int i = 0; i < argc; i++) {
            printf("argv[%d] = %s\n", i, argv[i]);
        }
        
    }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    You can't extend argv itself, but you can copy it's pointers to another char** and extend that.

    BTW, what you're doing with argc makes no sense. You're just setting it back to the value it already had.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void init(int argc, char **argv) {
        for (int i = 0; i < argc; i++)
            printf("argv[%d] = %s\n", i, argv[i]);
    }
    
    int main (int argc, char **argv) {
        int ext_argc = argc + 1;
        char **ext_argv = malloc((ext_argc + 1) * sizeof *ext_argv); // +1 for NULL
    
        for (int i = 0; i < argc; i++)
            ext_argv[i] = argv[i];
        ext_argv[argc] = argv[argc - 1];
        ext_argv[ext_argc] = NULL;
    
        init(ext_argc, ext_argv);
    
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inteface extending another interface
    By High Voltage in forum C++ Programming
    Replies: 6
    Last Post: 03-12-2017, 10:06 AM
  2. Extending wireless range?
    By bertazoid in forum Tech Board
    Replies: 1
    Last Post: 05-18-2009, 08:49 AM
  3. Malloc for extending the size....!
    By patil.vishwa in forum C Programming
    Replies: 5
    Last Post: 09-11-2008, 03:34 AM
  4. extending ostream
    By ilear_01 in forum C++ Programming
    Replies: 3
    Last Post: 06-10-2003, 11:27 PM
  5. extending a month calander to a year
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 02-03-2002, 06:39 AM

Tags for this Thread