The segmentation fault, if not caused by something else first will be caused here:
number = argv[1][square];//seg fault possible when square becomes
//larger than strlen(argv[1]) + 1
Attempting to access memory that the program process does not own, as above, will invoke undefined behavior.
Also, at the time this expression is executed:
square = number * number;
it is unknown what value was contained in square
.
These two values should be initialized:
int number = 0;
int square = 0;//this specifically will cause problems later if not initialized
Also, at the time this is called:
number = argv[1][square];
argv[1]
is a string, and needs to be converted to an integer before using.
number = atoi(argv[1]);
Next, the statement:
number = argv[1][square]; //seg fault possible as noted above.
will blow up when the value of square
becomes larger than then string length of argv[1]
.
If your intent is squaring the value contained in argv[1]
in its entirety as a single numeric value, it must first be converted from a string array, to an integer value, then you can easily get the square as you do in your code:
int number = atoi(argv[1]);
square = number * number;
If, as it appears in your code, you are interested in squaring each of the component integers making up the string, then given the input of "1234, to convert each of the digits in
argv1from ASCII value to its numeric value. (i.e.
val = argv1[x] - '0'==>
x`), then square it, then move the the next character in the array and so on.... look at the other part of this answer below.
The following is an adaptation of your original to do this...
int main(int argc, char *argv[]) {
int number = 0;
int square = 0;
if(argc != 2)
{
printf("%s\n","Usage prog.exe <nnn>, where nnn is an integer value.\nProgram will exit.");
}
else
{
char *ptr = argv[1];
while(*ptr != '\0')
{
number = *ptr - '0';
square = number * number;
printf("%d\n", square);//write() not available on my system, replace as necessary
square++;
ptr++;
}
}
return 0;
}
So, for example given prog.exe "1234"
, the output is: