I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
char* passwd;
int nr;
void test()
{
int i=0;
for(i=0;i<argc;i++)
printf("Hello %s \n",user);
}
int main(int argc,char*argv[])
{
int i;
nr=argc;
for (i=0; i<argc; i++)
{
user=strdup(argv[i]);
}
test();
return 0;
}
The result is the argv[argc] on all the positions. How can I fix this? I wwant to have that test() outside the loop.
**
EDIT
** After the ANSWERS here this is my new code, which is not working. Can anyone say why?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
void test(int n)
{
int i=0;
for(i=0;i<n;i++)
printf("%s \n",user[i]);
}
int main(int argc,char*argv[])
{
user = (char*) malloc(argc*sizeof(char));
int i;
for (i=0;i<argc;i++)
{
user[i]=argv[i];
}
test(argc);
return 0;
}
malloc(argc*sizeof(char*)). You want an array ofchar*, but forgot the*in thesizeofargument. And you must declareuseras achar**.argv[i]is a pointer tochar. You (try to) assign that touser[i], for that to work,user[i]must be compatible withchar*, so user should be either an array ofchar*- likechar *user[100];if the size is known beforehand - or a pointer to a block of memory used as an array ofchar*. The type of thing thatuserpoints to must then have the size of achar*for the indexing to work properly. The things pointed to by user must have the size ofchar*, and they're used aschar*, so the proper thing is to declare them aschar*, anduseras a pointer tochar*.