1 Replies - 143 Views - Last Post: 04 October 2012 - 04:18 PM Rate Topic: -----

#1 toshikazu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 04-October 12

Question using arrays and "For Loop" statements

Posted 04 October 2012 - 04:15 PM

I new to programming and I don't fully quite understand how to properly assign and carry out a char array within a 'for loop' statements. I attempted to do a basic task by declaring a character array to hold up to 15 characters, ask user my name, and storing it into the character array.

This is what I have attempted so far:


#include <string.h>

int main (void)
{
char name [20];

printf("Enter name\n");
scanf("%s", &name [20]);

}



Is This A Good Question/Topic? 0
  • +

Replies To: Question using arrays and "For Loop" statements

#2 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1074
  • View blog
  • Posts: 4,533
  • Joined: 09-June 09

Re: Question using arrays and "For Loop" statements

Posted 04 October 2012 - 04:18 PM

scanf accepts a "pointer" to a piece of memory to write to. An array of characters is some what like a pointer, it is simple an address to the first element in the array.

You can pass an array to scanf like so
#include <string.h>

int main (void)
{
   char name [20];

   printf("Enter name\n");
   scanf("%s", name); //no need to take the address of with &

}




The thing about scanf is that it will write as many characters as you type to your name buffer. But what do you think happens if you type 21 characters?

link on pointers: http://pw1.netcom.co...tr/pointers.htm

This post has been edited by jjl: 04 October 2012 - 04:19 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1