Reputation: 167
I am experimenting with pointers and strings. In the following code, everything is tested (you can compile and run yourselves), but I keep crashing when I am trying to use strcmp. The code runs without warnings in codeblocks. Can you please point out my mistake that makes the program crash??
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int choice,x=7,k,q,cmp,j=0,i=0,N;
char v[5],str[80],c[5];
char *B[11][2]=
{"-----","0",
".----","1",
"..---","2",
"...--","3",
"....-","4",
".....","5",
"-....","6",
"--...","7",
"---..","8",
"----.","9",
NULL,NULL};
printf("Give a stream");
if(gets(str)) printf("%s\n",str);
fflush(stdin);
i=0;
while(str[i])
{
q=0;
j=i+1;
while(q%5!=0)
{
v[j]=str[j];
puts(v);
j++;
q++;
}
printf("Hello");
for(k=0; k<11; k++)
{
strcpy(c,B[k][0]);
printf("%s",c);
x=strcmp(v,c);
//Problem:
printf("%d",c);
if(x==0) printf("hi");
}
i=i+1;
j++;
}
}
Upvotes: 2
Views: 1557
Reputation: 2887
This program will dump when k=10,because B[10][0] = NULL.strcpy(char *dest, const char *src) will dump when src=null.
Upvotes: 1
Reputation: 18358
You aren't filling the v
with data. The condition while(q%5!=0)
is false on entry since q == 0
. This leaves v
uninitialized, i.e. containing garbage.
Upvotes: 1
Reputation: 455252
You are doing:
strcpy(c,B[k][0]);
Now c
is declared as:
char c[5];
and B[k][0]
has 5 characters. Since you want c
to be a NUL terminated char array, you must has space to accommodate the NUL char and use strncpy
Upvotes: 1