Wanting to use char* or char[MAXLEN] as a string as I had in a recent class, but am unable to remember how it was done in the class. I remember most of the control statements regarding the technique (though they are pretty standard and may not be much help), and have included the sample below.
Run-time error at point marked in code
The eventual goal is to search for a string in the str string.
// Finding a part of a string
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 1024
void printStr(char str[]) {
int i = 0;
puts("String entered:");
for (i = 0; str[i] != '\0' && i < MAXLEN; i++) // error occurs here
printf("%c\n", str[i]);
}
void setString(char str[]) {
puts("Enter text to be added to string:");
scanf("%s", &str);
printStr(str);
}
void findText();
int main(void) {
char str[MAXLEN];
setString(str);
// findText();
return EXIT_SUCCESS;
}
you have a pointer mistake.
scanf into &str is wrong, str is already a char* so you are making it char** which is wrong. take the & off, and make sure you don't do that same error elsewhere.
fyi strstr finds a substring in a string or returns null pointer if not found.
It seems like having a type char** is something the compiler should point out, and my compiler has been known to do weird things in the past. Is there something wrong with it?
maybe. Be sure you turned on maximum warnings and see if it tells you then. If it does not, try a different compiler. Most (All?!) of the major ones would have caught this issue.
Ah, my bad. I got the program working besides the fact that the printStr function will not print anything past a space character. In my for loop, I have the exit condition: str[i] != '\0'
which does not seem to be working properly. What is the error in my logic?
str[i] != '\0' is the proper way.
A problem is that scanf will terminate when it encounters a whitespace.
Better use fgets for your input.
This should work:
// Finding a part of a string
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 1024
void printStr(char str[])
{
int i = 0;
puts("String entered:");
for (i = 0; str[i] != '\0' && i < MAXLEN; i++) // error occurs here
printf("%c\n", str[i]);
}
void setString(char str[])
{
puts("Enter text to be added to string:");
fgets(str, MAXLEN, stdin);
printStr(str);
}
void findText();
int main(void) {
char str[MAXLEN];
setString(str);
// findText();
return EXIT_SUCCESS;
}
at least that is what i use on c++ / g++
your IDE should have a way to enable this.
FWIW I have a 4 year degree and decades of coding. And I turned my back for just a couple of years and found the language has changed so much I barely recognize some of the code people post.
I learned some progarmming 25+ years ago in school. I learned most from the examples that came with Turbo Pascal and Turbo C++ and reading lots of books.