C program is skipping code statements while compiling and executing [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The following code is for searching a string or character in another string :-
`
#include<stdio.h>
#include<string.h>
int strindex( char primary[] , char searchfor[]){
int k;
for(int i = 0 ; primary[i] != '\0' ; i++){
for(int j = i , k = 0 ; (searchfor[k] != '\0') && (primary[j] == searchfor[k]) ; j++ , k++){
;
}
if( k > 0 && searchfor[k] == '\0'){
return i;
}
}
return -1;
}
int line( char *str ){
int i = 0;
char c;
for (;(c = getchar()) != '\n' && (c != EOF) ; i++){
str[i] = c;
}
if( c = '\n') str[i] = '\n';
str[++i] = '\0';
return i;
}
int main(){
char str1[100] , str2[100];
int i ;
puts("Enter the main string:-");
line(str1);
puts("Enter string to search for:-");
line(str2);
i = strindex(str1 , str2);
if( i >= 0){
printf("String found at index : %d \n",i);
}else{
puts("stirng not found.");
}
puts("");
return 0;
}
`
The compile result :-
PS E:\Workspace\C> gcc p1.c
PS E:\Workspace\C> ./a.exe
Enter the main string:-
this is a demo text
Enter string to search for:-
demo
PS E:\Workspace\C>
I am using visual studio code ,
As we can see that the "if-else" and "print" statements after the function call are not being executed . I have tried a lot , but could not make it . Please someone help me and tell me where I am going wrong ??

int k;
for (int j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);
That k in the for loop is not the k declared before it, it's a new variable that shadows (hides) the original. That's because using int inside the for loop is a new declaration for all variables following it.
Then, when it comes time to doSomethingWith(k), that's using the original k, as the other one has gone out of scope.
And, since that original k will have some arbitrary value, hilarity will ensue :-)
The quickest solution is probably to remove the declaration from the for statement:
int j, k;
for (j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);
In your case, that would be along the lines of:
int strindex(char *primary, char *searchfor) {
int j, k;
for (int i = 0; primary[i] != '\0'; i++) {
for (j = i, k = 0; (searchfor[k] != '\0') && (primary[j] == searchfor[k]); j++, k++);
if (k > 0 && searchfor[k] == '\0') return i;
}
return -1;
}
As an aside, this is also a problem (in line()):
if (c = '\n') str[i] = '\n'; // First = should be ==, anyway.
str[++i] = '\0';
It preserves the newline character so that you would be looking for "demo\n" in "this is a demo text\n", which won't be found. Better to just use:
str[i] = '\0';
And, on top of that, c should be an int, not a char. That's because it has to cater for all possible char values and EOF.

Related

Why am I getting a Seg-Fa

So I apologize for the general question. I haven't been able to find anything that speaks to my specific case. If there is something out there and I missed it, I'm sorry.
I am writing a function that reverses a string. It's for a project that comes with some pretty specific guidelines. I'm not allowed to use any functions such as malloc, printf etc and my function needs to return the string that is passed in as an argument. The function needs to be prototyped as follows:
char *ft_strrev(char *str);
This is my funtction:
char *ft_strrev(char *str)
{
int i;
int j;
char c;
i = 0;
j = ;
c = '0';
while(str[j] != '\0')
j++;
while(i != j)
{
c = str[i];
str[i] = str[j];
str[j] = c;
i++;
j--;
}
}
When I call this in a main and test it with putstr https://github.com/kigiri/userpref/blob/master/ft_42/ft_putstr.c it compiles fine, but at runtime I get a seg fault.
What am I doing wrong?
There are two problems with your code (apart from this j =; stuff.
After the first while look j points to the '\0' after the end of the string rather than to the last character of the string.
Condition of the second look does handle the situation when j - i is odd initially. for example, if i is 0 and j is 1 initially, then, after first iteration, i will be 1 and j will be 0, so condition will still be true.
Here is fixed code:
char *ft_strrev (char *str)
{
int i = 0, j = 0;
while (str [j] != '\0') j++;
while (i < --j) {
char t = str [i];
str [i++] = str [j];
str [j] = t;
}
return str;
}

char-Tables, Segmentation Error

I'm currently learning the C programming language, and I'm having some issues with it.
I'm getting Segmentation Error quite a lot when dealing with string (A.K.A char tables)
Here a simple algorithm just to delete the 'e' letter in the input string.
Example:
"hackers does exist" ->>> "hacks dos xist"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
char T[200];
int j,i,l,times=0;
printf("Entre THE TXT\n");
gets(T);
while (T[i] != '\0')
{
l++;
i++;
}
for (i=0;i<l;i++)
{
if ( T[i] == 'e')
{
times++;
}
}
l=l-times;
i=0;
j=0;
while (i<l)
{
if ( T[j] != 'e')
{
T[i]=T[j];
i++;
j++;
}
else j++;
}
for (i=0;i<l;i++)
{
printf("%c",T[i]);
}
return 0;
}
Can you please tell me what I did wrong?
PS: I have noticed that each time I do incrementation as j++ in this code I will get the Segmentation Error... I really don't understand why.
Initialize i, j, l variables. Since uninitialized local variables are indeterminate. Reading them prior to assigning a value results in undefined behavior.
You are accessing the i and l variable without initialization.
while (T[i] != '\0')
{
l++;
i++;
}
Initialize as below.
int j = 0, i = 0, l = 0, times = 0;
As kiran Biradar already answered you only missed to initialize your integers.
You have several options here. I'll write them from most common to most discouraged.
Most used form, verbose but easier to maintain later.
int i = 0;
int j = 0;
int l = 0;
int times = 0;
Short form 1:
int i = 0, j = 0, l = 0, times 0;
Short form 2:
int i, j, l, times;
i = j = l = times = 0;
I'd suggest you also to use the features of at least the C99 Standard and reduce the scope of your variables completely. (Yes I know it's possible with {}-Blocks but I kinda like for-loops, if you iterate completely over something.
Hence my suggestion for your code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // str(n)len
int main(void) // argv/argc is never used
{
char text[200];
printf("Entre THE TXT\n");
if (fgets(text, sizeof(text), stdin) == NULL) // fgets as gets is deprecated
exit(EXIT_FAILURE);
size_t len = strlen(text); // returns number of Characters excluding '\0'
if (len > 0 && text[len-1] == '\n') { // strip newline if present from fgets
text[len-1] = '\0';
}
unsigned int times = 0;
for (size_t i=0; i<len; i++) {
if (text[i] == 'e') {
times++;
}
}
// I'd prefer to use a `newlen` variable
len -= (size_t) times;
for (size_t j=0, i=0; i < len; j++) {
if (text[j] != 'e') {
text[i] = text[j];
i++;
}
}
text[len] = '\0'; // just for safety reasons terminate string properly
puts(text); // Use puts instead of calling printf several times.
return 0;
}
Further improvements:
Actually the times could be eliminated, as it's not really used to delete es.
So just remove the times block and all lines with it.

Program wont exit with EOF and wont print if last character is ' [space]'

I am new to C so please forgive my misunderstandings. I am trying to write a simple program that takes a users character input, mutates it, and prints it out in "piglatin"... where the first letter of a word is moved to the end of the word and then an "ay" is appended to the end of the word. Example-> the word "like" becomes ... "ikelay". Here is my program...
//pig latin
#include <stdio.h>
#define MAX 1000
void pigify(char chars[], int cnt);
void sortWords(char stream[], int total);
void clearWord(char word[], int j);
int main(){
int c, i;
char allChars[MAX];
i = 0;
while((c = getchar()) != EOF){
allChars[i] = c;
++i;
}
allChars[i] = '\0';
sortWords(allChars, i);
return 0;
}
/////////////////
/////////////////
void sortWords(char stream[], int total){
int i, j, start, end, m;
char words[total];
clearWord(words, total);
i = j = end = m = 0;
while(stream[i] != '\0'){
if(stream[i] != '\n' && stream[i] != '\t' && stream[i] != ' '){
++i;
++j;
} else if (j > 2){
end = i;
for(start = i-j; start <= end; ++start){
words[m] = stream[start];
++m;
}
pigify(words, m);
clearWord(words, m);
j = m = 0;
}
}
}
/////////////////
/////////////////
void clearWord(char word[], int i){
int j;
for (j = 0; j <= i; ++j){
word[j] = '\0';
}
}
/////////////////
/////////////////
void pigify(char alls[], int cnt){
int j;
char pchars[cnt+3];
j = 0;
while(alls[j] != '\0'){
pchars[j] = alls[j];
++j;
}
if(alls[0] != 'a' && alls[0] != 'e' && alls[0] != 'i' && alls[0] != 'o' && alls[0] != 'u'){
pchars[cnt] = alls[0];
pchars[cnt+1] = 'a';
pchars[cnt+2] = 'y';
pchars[cnt+3] = '\0';
pchars[0] = ' ';
}
printf("\npost pigification --> %s\n", pchars);
}
I have been on it for a long time and I can't find where i've made a mistake. I do not care so much about the program, I don't need to convert input to "piglatin" but I would really love to know what I have done wrong!!! Help, advice, and/or pointers would be awesome! thank you
Writing outside array bounds. Use <
char words[total];
clearWord(words, total);
void clearWord(char word[], int i){
int j;
// for (j = 0; j <= i; ++j){
for (j = 0; j < i; ++j){
word[j] = '\0';
}
}
May have other problems too
Replace this line:
while((c = getchar()) != EOF){
allChars[i] = c;
++i;
}
With this:
while ((allChars[i] = getchar()) != '\n')
i++;
Otherwise, every time you press enter, the loop starts over. Maybe someone else can explain that, but the above code will let your code do what you want it to.
In the future, a function such as fgets() may be more suitable for your needs, as you don't have to worry about checking for EOF and such - you just have to strip the newline at the end in that case.
With help form #chux and after using some more print statements to find out what is going on, I realized that in the function sortWords the variable i was not being incremented for the case in which a space '' '' character or a new line or tab character ''\n'' and ''\t'' was reached. After changing the function to this ...
void sortWords(char stream[], int total){
int i, j, start, end, m;
char words[total];
clearWord(words, total);
i = j = end = m = 0;
while(stream[i] != '\0'){
if(stream[i] != '\n' && stream[i] != '\t' && stream[i] != ' '){
++i;
++j;
} else if (j > 2){
end = i;
for(start = i-j; start <= end; ++start){
words[m] = stream[start];
++m;
}
pigify(words, m);
clearWord(words, m);
j = m = 0;
++i;
}
}
}
The program works at least somewhat more as expected. The bugs i set out to solve with this question are fixed at least. Still not perfect but i think this was a poorly asked question on my part and should be ended

Reading in grid of characters in C

I am working on a word search assignment for my C class. I need to read in a grid of characters from the console by using the redirection operator such as
./a.out < data1
I am not reading in the data from a file, so I don't need to use file operations. I need to read this grid in and then store it in a 2D array. However, my code just reads in the first line of the grid and stops. Here is my code:
int main(void) {
char inputGrid[50][50];
char solvedGrid[50][50];
char inputString[50];
char ch;
int inputRow = 0;
int rowLength = 0;
int i = 0;
size_t r;
size_t c;
scanf("%[^\n]%*c", inputString);
rowLength = strlen(inputString);
for (r = 0, c = 0; r <= rowLength; r++) {
if (inputString[r] == '\n') {
scanf("%[^\n]%*c", inputString);
inputRow++;
if (inputString[r] != ' ') {
inputGrid[inputRow][c] = inputString[r];
c++;
}
} else
if (inputString[r] != ' ') {
inputGrid[inputRow][c] = inputString[r];
c++;
}
}
// Print the array
for (r = 0; r < strlen(inputString); r++) {
for (c = 0; c < strlen(inputString); c++) {
printf("%c", inputGrid[r][c]);
}
printf("\n");
}
}
I need to read in the data in the form of space separated characters that form a square matrix. Any help would be appreciated.
Each time through the loop, you increment r even though, at most, you have read a single character. You might find it easier to use nested loops: a loop to keep track of the rows/lines, and a loop inside that one to process each character within that row/line.
scanf("%[^\n]%*c", inputString) doesn't store \n in inputString, hence the test inputString[r] == '\n' will never be true.
You could use
int i, r, c;
while (scanf("%[^\n]%*c", inputString) > 0)
{
for (rowLength = i = 0; i < strlen(inputString); ++i)
if (inputString[i] != ' ')
inputGrid[inputRow][rowLength++] = inputString[i];
if (++inputRow >= rowLength) break;
}
// Print the array
for (r = 0; r < inputRow; ++r, printf("\n"))
for (c = 0; c < rowLength; ++c)
printf("%c", inputGrid[r][c]);

ANSI C programming [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
On page 69 from ANSI C programming by K&R there is an example of a function that works as a special version of Unix program grep.
The code is:
#include <stdio.h>
#define MAXLINE 1000 //max input length
int getlinee(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";
int main ()
{
char line[MAXLINE];
int found =0;
while (getlinee(line,MAXLINE) > 0)
if (Strindex(line, pattern)>=0){
printf("%s", line);
found ++;
}
return found;
} // end of main function
int getlinee (char s[], int lim)
{
int c,i;
i =0;
while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')
s[i++] =c;
if (c =='\n')
s[i++] =c;
s[i] = '\0' ;
return i;
}
int Strindex (char s[], char t[])
{
int i,j,k;
for (i =0; s[i] != '\0'; i++)
for (i =i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
} // end of strindex
when I compile it I get
51:1:error: expected identifier or '(' before 'return'
54:1:error: expected identifier or '(' before '}' token
I checked the code number of times and couldn't spot out the error.
Remove your extra
return -1;
} // end of strindex
Also you #include is empty.You are not using any header file.
You have two problems in your code.
(i). Line number 40:
for (i = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
Compiler may raise an error for i = i as Assignment to itself 'i = i'
(ii). Line number 45:
An extra }. Delete this. Then try to build. I make changes your code and it successfully built.
#include <stdio.h>
#define MAXLINE 1000 //max input length
int getlinee(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";
int main()
{
char line[MAXLINE];
int found = 0;
while (getlinee(line, MAXLINE) > 0)
if (Strindex(line, pattern) >= 0) {
printf("%s", line);
found++;
}
return found;
} // end of main function
int getlinee(char s[], int lim) {
int c, i;
i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
int Strindex(char s[], char t[]) {
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
for (i = 1, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0')
return i;
return -1;
} // end of strindex
}
return -1;
Remove } brace above line with return operator.
If we judge by indent and code structure, I think there's open parentheses missing in line:
for (i =0; s[i] != '\0'; i++)
in last function. So the actual line should look like:
for (i =0; s[i] != '\0'; i++) {
There are more than one error in last function. Another one is that j is not initialized.
As I can conclude, that function should search for index of substring inside string. First loop passes through string s. Second loop passes through second string and compares two strings. If comparison reaches the end of second string, it returns found index, else function exits with index -1.

Resources