1.11M Members

function / array help

 
0
 

does any one know why my for loop work fine but printf("%c",num[0]); get me 0?

void test(char[]);
void test2(char[]);

int main(void)
{
  char num[10];
  test(num);
  test2(num);
}

void test()
{
   num[0] = '1';
   num[1] = '2'
}


void test2(int num[])
{
  for(a = 0; a < 10; a++)
 {
  printf("%c",num[a]);


  printf("%c",num[0]);

  
 }
}
 
0
 

That doesn't compile.

 
0
 

The num[] array is a local variable to main(). You need to make it global for this to work. Just move the declaration outside of main, as in:

void test(char[]);
void test2(char[]);

char num[10];
 
int main(void)
{
  test(num);
  test2(num);
}
 
void test()
{
   num[0] = '1';
   num[1] = '2'
}
 
 
void test2(int num[])
{
  for(a = 0; a < 10; a++)
 {
  printf("%c",num[a]);
 
 
  printf("%c",num[0]);
 
 
 }
}

It's still beginner's code, but it should work (not tested, not certified).

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: