Click to See Complete Forum and Search --> : Should be simple, but can't get it...


Strike
10-13-2000, 03:04 PM
Okay, find where I went wrong with this, it's segfaulting on me (as far as I can tell, I calloc()ed the right amount and am not running past the end of the array, but then again, I'm used to C++ dynamic memory management). I was going to debug this myself, but DDD is taking forever to download and I'm not handy enough with gdb by itself to work with it ... *sigh*

Right now it's just (supposed to be) reading the command-line arguments into my integer array that I creatively named array and printing them (but that's just to test and make sure I'm referencing the indices right):

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
int *array;
int i;

if (argc < 3) {
printf("Usage: euclid-gcd n1 n2 [n3 [n4 ... ]]]]\n");
exit(1);
}

array = (int *)calloc((argc-1), sizeof(int));

for (i=0; i<(argc-1); i++) {
array[i] = atoi(argv[i-1]);
printf("i = %d, array[i] = %d", i, array[i]); /* Diagnostics */
}

return 0;
}


This is not the code for the whole program, because I have other functions I will perform on that array once it is read in correctly, but this is what is giving me the error. TIA

kmj
10-13-2000, 03:11 PM
for (i=0; i<(argc-1); i++) {
array[i] = atoi(argv[i-1]);
}

Wouldn't the first time through access argv[-1]?

Keith M
10-13-2000, 03:11 PM
Well you start i at 0, then index argv with i-1. That's definitely bad. I think you want argv[i+1], because isn't the first thing in argv the program name from the command line?

Strike
10-13-2000, 03:15 PM
Bah, I'm a moron. Thanks, both of you. Keith M is right, I should have done a + instead of a -
Chalk another one up to "Stupid Programmer Error"

TheLinuxDuck
10-13-2000, 03:22 PM
for (i=0; i<(argc-1); i++) {
array[i] = atoi(argv[i-1]);
printf("i = %d, array[i] = %d", i,
array[i]); /* Diagnostics */
}


I think you're wanting something more like:

for (i=1; i<argc; i++) {
array[i-1] = atoi(argv[i]);
printf("i = %d, array[i-1] = %d", i-1,
array[i-1]); /* Diagnostics */
}


That way, you're starting past the program name, but stopping before the last argument.

Btw, is there any particular reason why you're using calloc instead of malloc? If you don't need to numbers preset to 0, it seems that calloc is doing an extra step uneeded.. just my .0002... http://www.linuxnewbie.org/ubb/smile.gif

------------------
TheLinuxDuck
Wait... that's a penguin?!?!?
:wq