Question
How to declare a string variable in C?
Background
In my quest to learn the basics of c, I am trying to port on
Normally we use "&" in scanf but you shouldn't use it before variable "name" here. Because "name" is a char array. When the name of a char array is used without "[]", it means the address of the array.
The int your putting is not a string, a string looks like "char myString[20]". Not like "int name", that's an integer and not a string or char. This is the code you want:
int main(int argc, const char * argv[])
{
char name[9999];
printf("What is your name?\n");
scanf("%s", name);
system("cls");
printf("Your name is %s", name);
return 0;
}
char name[60];
scanf("%s", name);
Edit: restricted input length to 59 characters (plus terminating 0):
char name[60];
scanf("%59s", name);
Just put this line below, atop of your main()
function.
typedef string char*;
This allows you to create a string variable as you do with integers or characters in C. After that, your program should look like this:
#include <stdio.h>
typedef char* string;
int main(void) {
string a = "Hello";
printf("%s\n", a); // %s format specifier for String
return 0;
}
For a live demonstration, visit this REPL.it.
C does not have a string variable type. Strings can be stored as character arrays (char variable type). The most basic example I would add up to the rest is:
int main()
{
char name[] = "Hello World!";
printf("%s",name);
return(0);
}
In C you can not direct declare a string variable like Java and other language. you'll have to use character array or pointer for declaring strings.
char a[50];
printf("Enter your string");
gets(a);
OR
char *a;
printf("Enter your string here");
gets(a);
OR
char a[60];
scanf("%59s",a);