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 ?
Related
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 3 years ago.
Improve this question
I seem to be unable to understand why do these two cases behave differently:
const char* TEXT = "hello world!";
int length = (int) strlen(TEXT);
char* array[length];
this is ok, however this one:
char* text;
scanf("%[^\n]s", text);
// input "hello world!" and press enter
int length = (int) strlen(text);
char* array[length];
ends with a segmentation fault
what am I missing?
For the scanf call, text parameter, you do not allocate any memory. You also do not initialize the variable to a value. This results in scanf writing to random memory, which causes your segmentation fault.
To fix this issue you need to allocate a buffer of a reasonable size:
char* text = malloc(1024);
1024 is the maximum size that you expect the input data to be. This, however, still leaves the code vulnerable to buffer overflows. To prevent buffer overflows you can inform scanf that text is of a certain size; look for the answers here
If you do not want to allocate the memory yourself, scanf can do it for you:
Note that the POSIX 2008 (2013) version of the
scanf()
family of functions supports a format modifier m (an
assignment-allocation character) for string inputs (%s, %c, %[).
Instead of taking a char * argument, it takes a char ** argument,
and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf() function fails to satisfy all the conversion
specifications, then all the memory it allocated for %ms-like
conversions is freed before the function returns.
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 6 years ago.
Improve this question
I have the following code:
char* realtor_command[120];
for(int i=0;i<REALTOR_MAX_COMMAND_LENGTH;i++){
realtor_command[i]=malloc(sizeof(120));
}
realtor_command[0]="test_string"
realtor_command[1]="next_test_string"
When I use strlen(realtor_command[0]) I get wrong value, I read in previous questions this happens because its an array and not pointer, yet I haven't found any fix for this problem.
My question is if there is anyway to get the length of realtor_command[i]?
Thank you very much.
EDIT :
This is how I invoke strlen :
char* matrix=malloc(strlen(realtor_command[8])+1);
In this code:
char* realtor_command[120];
for(int i=0;i<REALTOR_MAX_COMMAND_LENGTH;i++){
realtor_command[i]=malloc(sizeof(120));
}
You create an array of 120 strings, then loop through REALTOR_MAX_COMMAND strings (presumably this should be 120?) and set them to newly allocated 4- or 8-byte strings (sizeof(120) means sizeof(int) which is either 4 or 8 bytes). Since those strings are newly allocated, they will contain arbitrary data, and may not end with a null-terminator.
This is important because strlen() just loops over the string until it finds a null terminator, so it can't work with non-null-terminated strings.
You could add a null terminator yourself, but then the strings would contain arbitrary garbage up to the end of the string, and they may have null terminators inside them. You could make them start with a null-terminator, but then strlen() would always return 0.
What might be better is to allocate these strings when you actually fill them, and leave them as null pointers until then:
char* realtor_command[120];
for (int i = 0; i < 120; i++) {
realtor_command[i] = NULL;
}
char input_buffer[REALTOR_MAX_COMMAND];
// Read in one string, then copy it so we can re-use the buffer
fgets(input_buffer, REALTOR_MAX_COMMAND, stdin);
realtor_command[0] = strdup(input_buffer);
This will also avoid the memory leak in your code.
Note that you'll probably want to make sure the string read by fgets contains a newline, to make sure the input fit in your buffer:
if (strstr(input_buffer, "\n") == NULL) {
// error, input didn't fit in our buffer!
}
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.
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 am checking input and need a way to compare to the actual word 'int'.
Example:
char t[10] = "int";
if (t == 'int'){
printf("We have an integr");
}
I'm not sure if this is possible or not, still learning the ropes of C. Thanks for the help!
You can use strcmp to compare the text. Note that it returns a zero on a match:
if (strcmp(t, "int") == 0) {
printf("We have an integer\n");
}
"int" is a string literal. It has nothing to do with the int type or any value of said type. The exact same problem exists if using "foobar" with the original code. A string is a string.
Using 'int' (or 'foobar') is also wrong, because those are [confusing] character literals (of type char) and not string literals (of type char*). The compiler should have generated a warning or two - enable and read all warnings! - even though it compiled.
And finally, see the other answers for how to correctly compare strings in C which explain why the == approach doesn't work.
The declaration char t[]="int"; includes the null terminator for using with strcmp(), while not using unecessary memory while providing the string version of int you are looking for.
Note: Using the == operator will not work for a string comparison unless you check each char element, one at a time. (see second example below)
char t[] = {"int"};
if (strcmp(t, "int")==0){
printf("We have an integr");
}
Using ==:
if((t[0]=='i')&&(t[1]=='n')&&(t[2]=='t')&&(t[3]=='\0')){...
would also work
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.