c++ - Transferring argv into a new array -


i can't figure out why code not working. have seen this still didn't it. segmentation fault (11) , not see argv array printed testarray.

my code far

#include <iostream>  int main(int argc, char**argv) {      char testarray[argc];      (int i=0; argc; i++){         std::cout << argv[i] << std::endl;         testarray[i] = *argv[i];     }      (int i=0; argc; i++){         std::cout << testarray[i] << std::endl;     }      return 0; } 

in code, change

  (int i=0; argc; i++){ 

to

  (int i=0; < argc; i++){ 

otherwise, there apparently no conditional check for loop (argc >= 1 , unchanged, usually), transforming infinite loop.

fwiw, unbound increment of i causes testarray[i] access out-of-bound memory causes undefined behaviour.


that said, there more bothered. there nothing called c , c++ code. different , should tread way. please not mix them up. each of them have own advantages/disadvantages, use whichever suits you, not both in code.

now, regarding copying of array, argv pointer argv[i]s, holds command line arguments. *argv[i] not give whole array @ time, points first element in argv[i] array. so,

 testarray[i] = *argv[i]; 

does not copy array. copy it,

in c

  1. you need allocate buffer of size strlen(argv[i]) + 1
  2. use strcpy() copy argv[i] buffer.

in c++

you need use std::copy().


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -