Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have written the following code and it works fine. But before I made changes i had entered a few statements which I expected would work but didn't. Just as a trial, i made changes and it worked. Please clarify what I was doing wrong. I am trying simple programs initially to make my understanding of Pointers better.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int i;
char *instring,*outstring;
char ch,p;
instring = (char*)malloc(15*sizeof(char));
outstring= (char*)malloc(15*sizeof(char));
printf("Enter the string:");
gets(instring);
printf("Enter the character to be removed:");
scanf("%c",&ch);
for(i=0;i<strlen(instring);i++)
{
if( *(instring+i) != ch)
{
*(outstring+i) = *(instring+i);
printf("%c",*(outstring+i));
}
}
Under if statement, I had written the following:
if(*(instring) != ch)
{
*outstring = *instring;
printf("%c",*(outstring));
instring++;
outstring++;
}
Why doesn't this work?
I'm not sure what you mean by not working, but if your non-working function looked like this:
for(i=0;i<strlen(instring);i++)
{
if(*(instring) != ch)
{
*outstring = *instring;
printf("%c",*(outstring));
instring++;
outstring++;
}
}
Then it looks like the problem is that you are only incrementing instring if it's current character doesn't match ch. So if instring's current character does match ch, you will loop forever and the process will hang.
Also, if all you want to do is print out the string without the character to be removed, you don't need outstring. Just do e.g.
printf("%c",*(instring));
On the other hand if you also want to store the string in outstring with the character removed, you can't increment the pointers in tandem like you are doing. Because when you hit the character to be removed, you want to increment the instring pointer to move past it, but not increment the outstring pointer since you haven't added anything to that string.
It does work. But you loose both strings (pointers to them)
Try to store pointers to the beginning of both strings in another two pointers (char*) and then do your cycle.
And at the end, print the pointers you stored before - because they still point to your strings. When you increment pointers instring and outstring, they don't point to your strings anymore - they point to the very end of these strings.
Play with it a little bit more and you'll see :)
edit: Well, no, I've been writing faster then reading, sorry. Your (another) problem is even sooner - comparison. You are comparing instring with character and you change it only if condition is true. So you are comparing the same thing over and over and over.
It's tough to tell, what your problem really is.
Related
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 7 years ago.
Improve this question
I tried inputting the null character into the list of delimiters but it would not accept it. I tried inputting "\0" but it wouldn't accept it. I even tried putting in the double quotes with escape characters but it still would not accept it.
Is there a way I could do this?
According to strtok(3) this function is used to isolate sequential tokens in a null-terminated string. So the answer is no, not using strtok, since that function cannot compare a \0 separator from the terminator. You will have to write your own function (which is trivial).
Also read the BUGS section in the strtok man page ... better avoid using it.
If you are allowed to end your string with a double \0 as sentinel you can build your own function, something like:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *s = "abc\0def\0ghi\0";
char *p = s;
while (*p) {
puts(p);
p = strchr(p, '\0');
p++;
}
return 0;
}
Output:
abc
def
ghi
For better or worse, C decided that all strings are null terminated, so you can't parse based on that character.
One workaround would be to replace all nulls in your (non-string) binary buffer with something you know doesn't occur in the buffer, then use that as your separator treating the buffer as char*.
In C, strings are just char arrays that must end with a null character. If a string in memory is not terminated that way, the program will endlessly read memory until a null char is found and there is no way to determine where it will be since memory changes constantly. Your best bet is to create an array of char pointers (strings) and populate them using better organization.
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 7 years ago.
Improve this question
I have this code. I want that when the user writes yes the program will print OK.
However, the program writes
"yes is undeclared".
How can I make the program treat to 'yes' as a word and not as a variable?
char a = ' ';
scanf("%c",&a);
if(a == yes)
{
printf("OK");
}
First thing first, 'yes' is not a word (sting, if you mean that), "yes" is.
That said, you're way out of league for the idea. One possible implementation can look like
First, you need to define an array for the input, like char a[12] = "no"; because you need to store more than one character as per your need. (the size used here is just indicative).
Scan the user input using scanf(), like scanf("%11s", a);
Use strcmp() from string.h, for comparison, like if (!strcmp(a, "yes")).
Another possible implementation could make use of an enum of "YES" and "no", take the user choice as integer and make use of the good old == comparison operator.
There are numerous problems in your code.
First of all, you declare a as a char (character) which means you can't compare it to "yes" because that's a string, or char array because this is C.
It's composed of 4 characters (3 for the text, 1 for the \0; in C "strings" are null-terminated so there has to be an ending character).
Declare your variable and read it like this:
#include <string.h> //you need this for string comparison
char a[10]; //arbitrary size, just make sure it's big enough for the input
scanf("%s", a);
//OR
fgets(a, sizeof(a), stdin); //use fgets if you need to read more than one word, scanf stops reading at whitespace
//don't use == to compare strings
if (!strcmp(a, "yes")){ //use quotes to delimit "words"
printf("OK\n");
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
code is :
int main() {
int i,last;
char TXT[500];
printf("Donnez un exemple ?\n");
gets(TXT);
last = strlen(TXT);
for(i=0;i<50;i++){
if (i==0){
strcpy(TXT[1],TXT[0]);
} else {
strcpy(TXT[i-1],TXT[i]);
}
}
getch();
return 0;
}
error in line : strcpy(TXT[1],TXT[0]);
What is the cause of the problem ?
The strcpy function takes two char* (technically, a char* and a const char*). Moreover, it is not allowed to pass strcpy overlapping buffers.
It looks like you wanted to write
TXT[i-1] = TXT[i];
(this would delete the leading character from the string).
for(i=1 /* one, not zero */ ; i<50 ; i++) {
TXT[i-1] = TXT[i];
}
Good, but I want to use strcpy. How?
You are not allowed to use strcpy without an intermediate buffer. If you must use strcpy, do it like this:
char TXT[500], TMP[500];
printf("Donnez un exemple ?\n");
fgets(TXT, 499, stdin);
strcpy(TMP, &TXT[1]); // Note that 'for' loop is no longer required
TXT is an array of 500 characters.
So, TXT[1] and TXT[0] are individual characters (just one single letter).
TXT[0] is the very first character in the array.
TXT[1] is the second character in the array.
The function strcpy expects you to pass POINTER-to-characters (type char*) for both parameters.
And instead, you're passing a single character.
Can you explain what the purpose of this program is?
Maybe we can help you fix it then.
TXT[i] is of type char. But strcpy expects parameters of type char* since it operates on null-terminated strings. Hence the compilation error.
As for how to fix it, that depends on what your code is trying to do. Perhaps all you meant to do was
TXT[1] = TXT[0];
STRING FUNCTIONS WORKS ON STRING NOT ON CHARACTERS
ARE YOU TRYING TO SWAP THE WORDS OR CHARACTERS ?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *v= "a";
char *o='e';
char * w='i';
char *e='o';
char *l='u';
char *u[1];
printf ("please enter your character\n");
scanf ("%c",& u);
if (u == v){
puts("the character is it a vowel\n");
}
if (u == o) {
puts("the character is it a vowel\n");
}
else
puts("the character is a constant\n");
system("PAUSE");
return 0;
}
i need help in getting the right answer in finding a vowel from the user input.
First of all, shame on you for ignoring all of the compiler warnings you certainly received. They are there to help prevent you from doing "stupid things."
And why all this nonsense? This is the first of the "stupid things" the compiler is trying to tell you about.
char *v= "a";
char *o='e'; // invalid - Initializing a pointer to a constant 'e' (101).
char * w='i'; // invalid
char *e='o'; // invalid
char *l='u'; // invalid
Are you familiar with how pointers work? If not, I suggest you do some reading and understand them.
The first line makes sense - you're making a string and pointing char* v to that string.
But there's really no point in using pointer for those characters - or even variables at all. Just compare them directly:
char my_character;
if (my_character == 'a') {
// do something
}
And as for reading the character, again, you're using pointers when it doesn't make sense:
char *u[1]; // why?
Instead, just define a single char variable. Now, go look at the documentation for scanf. Giving it a format string of "%c" means, "I want to read just one character". Then, you need to tell where scanf to put it. You do this by passing it the "address of" the variable you want to store it in. You do this with (unsurprisingly!) the address of operator &.
char input_character;
scanf("%c", &input_character);
Armed with this information, you should be able to complete your work. Next, I suggest you look into the switch statement.
Finally, you must use consistent formatting (indentation, spacing) and use meaningful variable names, if you have any desire of ever being taken seriously as a programmer. Spelling out "vowel" for your pointless variables may be "cute" but it's total nonsense.
Most importantly, you should never write a single line of code, unless you understand exactly what it does. If you do this, then do not go asking anyone for help (especially not StackOverflow). If you can't explain what your code is doing (or at least what you think it's supposed to do), then you don't deserve for your program to work.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
#include
int main(void)
{
char str[100]="88888888888888";
char t[20]="";
gets(t);
puts(str);
puts(t);
return 0;
}
The first line
555555555555555555555555555555555
is put in.
Why str is 55555555555? Why str isn't 88888888888888888 or 55555555555588888?
You overriden the t buffer, and reached the str buffer, where the rest of the input, and the null terminator was set. And puts prints only until the null terminator.
Pretty much looks like that:
[ t (20) ][str(100) ]
55555555555555555555 5555555555555\0
Note that although t is declared as char[20], when you print it you get the full input (longer than 20), since puts stops at the null terminator (again).
BTW, this is a buffer overflow, not a stackoverflow, but stack overflow is possible on this codeas well.
As Binyamin said it is caused by the overflow you trigger because of the input string being too long. However it is a bit random thing - sometimes the two memory allocations will happen just next to each other and the string will extend to the neighbouring variables, sometimes it might not happen.
I advise you to place guard conditions for such kind of overflows.
If you see in the gets documentation:
Notice that gets does not behave exactly as fgets does with stdin as
argument: First, the ending newline character is not included with
gets while with fgets it is. And second, gets does not let you specify
a limit on how many characters are to be read, so you must be careful
with the size of the array pointed by str to avoid buffer overflows.
In your case if you do not know the size apriory maybe it is better idea to use fgets as it is more secure (though a bit slower).
When you enter a string of more than 20 5s, it overruns the buffer that was allocated to t and extends into the buffer that was allocated to str.
Then it displays the contents of str, which is the string you entered, starting at the 21st character.
Finally, it displays the contents of t, but since that string doesn't end with a null character, it continues displaying memory (which is the buffer assiged to str) until it encounters the null character after all the 5s.
In order to avoid those allocation overlapping issues you can try this alternative, so that the allocation takes place at runtime if I'm not wrong:
#include <iostream>
int main(void)
{
char *str;
char *t;
str = new char(100);
str = (char*)"88888888888888";
t = new char(20);
std::cin >> t;
puts(str);
puts(t);
return 0;
}