Reputation: 17
I am trying to learn string in c. I have written this program. I want this program will terminate for a particular word (press ENTER after typing the word). Its Compile well but after given input when I pressing enter it shows me this message: test.exe has stopped working. Here "test" is the name of my program. Please help me to understand this.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int i, j;
char *str[10];
for(i=0; i<10; i++)
{
//gets(str[i]);
scanf("%s",str[i]);
if(str[i]=="man") break;
}
for(j=0; j<10; j++)
{
printf("%s\n",str[j]);
}
return 0;
}
Upvotes: 1
Views: 11527
Reputation: 37701
For comparing strings in C, you can use strcmp
function. For example:
if(strcmp(str[i],"man") == 0){
# write your code here
}
And for initialization, do as follows.
char *str[10];
for(i=0; i<10; i++){
str[i] = malloc(sizeof(char) * 1024);
}
You can also do as following.
char str[10][1024];
for(i=0; i<10; i++){
scanf("%s", str[i]);
}
Alternative: If you want to declare str
as char **str
, you can follow the following approach.
char **str = malloc(10*sizeof(char*));
for(int i=0; i<10; i++){
str[i] = malloc(sizeof(char) * 1024); // buffer for 1024 chars
}
Upvotes: 3