Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting question

Status
Not open for further replies.

stevebiks

Programmer
Feb 13, 2005
10
US
Oaky bear with me cause i am very new to C however i know a bit of java.

I am trying to test out reading parametes from the command line, anyway they read in as character strings initially right? I want to read in a number, lets say 20. So anyway i want to save it as an int so i can manipulate later. i figured with this i would read it in as an array jsut cause the argv is an array too and it would be easier. here is what i worte to try and test it out. I read stuff in and the array comes out as NULL, but when i comment out my attempt at casting it outputs the everything just fine. any info or advice??

CODE::::

#include <stdio.h>

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

int array[4]; /* my array for storing as ints*/

printf("argc = %d\n", argc);

for (i = 0; i < argc; i++)
array=(int) argv; /* my attempt at casting*/


printf("argv[%d] = \"%s\"\n", i, argv);
}

Thanks in advance!!!!
 
In C, operators such as = are very simplistic and don't handle type conversions for you. The integer takes up a completely different amount of memory than the character string and trying to cast it is only taking an integer sized chunk of the data and converting it raw into the int variable. To convert the ASCII text into a number, use a function such as atoi().
Code:
array[i] = atoi(argv[i]);
 
Thanks a lot!!! that helps and your explaination helps me understand why. I really really appreciate it!!
-stevebiks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top