Frequently asked questions

  1. Is it possible to initialize a variable at the time it was declared?

Yes, you don’t have to write a separate assignment statement after the variable declaration, unless you plan to change it later on.  For example: char planet [15] = “Earth”; does two things: it declares a string variable named planet, then initializes it with the value “Earth”.

  1. What is the difference between a string copy (strcpy) and a memory copy (memcpy)?

Generally speaking, they both copy a number of bytes from a source pointer to a destination pointer. But the basic difference is that the strcpy() is specifically designed to copy strings, hence it stops copying after getting the first ‘\0′(NULL) character. But memcpy() is designed to work with all data types. So you need to specify the length of the data to be copied, starting from the source pointer.

  1. How do you declare a variable that will hold string values?

The char keyword can only hold 1 character value at a time. By creating an array of characters, you can store string values in it. Example: “char MyName[50]; ” declares a string variable named MyName that can hold a maximum of 50 characters.

  1. What is the difference between a string copy (strcpy) and a memory copy (memcpy)?

The strcpy() function is designed to work exclusively with strings. It copies each byte of the source string to the destination string and stops when the terminating null character () has been moved.On the other hand, the memcpy() function is designed to work with any type of data. Because not all data ends with a null character, you must provide the memcpy() function with the number of bytes you want to copy from the source to the destination.

  1. Reading String from user?

#include<stdio.h>

#include<conio.h>

void main()

{

char str[10];

printf(“Enter name: “);

scanf(“%s”,name);

printf(“Your name is: %s.”,name);

getch();

}

  1. gets() and puts()?Example?

gets() are used to get input as a string from keyword, using gets() we can input more than one word at a time

puts() are used to print output on screen, generally puts() function are used with gets() function.

Ex: #include<stdio.h>

#include<conio.h>

void main()

{

char str[10];

printf(“Enter any string: “);

gets(str);

printf(“String are: “);

puts(str);

getch();

}