I know it's not "best practice" returning pointers to local variables, but in this case I think i need it.
I'm writing a method to remove some characters at the beginning and some at the end of a string and return the result as a pointer to memory allocated in the function.
I developed the function separately, it worked, but when implemented with the rest of the code it doesn't return anything... It seems that the letters is added to the var new, but when i try printing the string, nothing is returned.... - char * prepareMessage(char str[]) {
-
int i=0, j=0, state=0;
-
-
while(str[i]==' ') { i++; } //skip whitespace
-
-
while(state == 0 && str[i]!='\0') { //find the start of the message (after 'new ')
-
if(str[i]=='n' && str[i+1]=='e' && str[i+2]=='w' && str[i+3]==' ') {
-
state = 1;
-
i += 4;
-
}
-
i++;
-
}
-
-
char * new = malloc(strlen(str)-i);
-
while(str[i]!='\0') { //copy the chars to the new var
-
*(new+j) = str[i++];
-
j++;
-
}
-
-
if(*(new+j-1)=='\"') { //remove trailing " and append \0
-
*(new+j-1) = '\0';
-
} else { //no trailing " - something wrong, free mem and return NULL
-
free(new);
-
return NULL;
-
debug("ERROR: NO TRAILING \"");
-
}
-
-
return new;
-
}
The str[] comes from - char inputBuffer[200] = "";
-
fgets(inputBuffer, 200, stdin)
Hope someone is able to point me in the right direction...
Thanks in advance!
7 2020 JosAH 11,448
Recognized Expert MVP
Just a few remarks:
1) your first two while loops can be replaced by a single strstr() function call.
2) your third while loop can be replaced by a single strcpy() function call.
3) why do you use two notations? i.e. s[i] and *(s+i)
kind regards,
Jos
Just a few remarks:
1) your first two while loops can be replaced by a single strstr() function call.
2) your third while loop can be replaced by a single strcpy() function call.
3) why do you use two notations? i.e. s[i] and *(s+i)
- char * prepareMessage(char str[]) {
-
int i=0;
-
char * new;
-
-
char * pMsgStart = strstr(str, "new ");
-
if(pMsgStart!=NULL) {
-
int i = (strstr(str, "new ")-&str[0])+5;
-
new = malloc(strlen(str)-i);
-
strcpy(new, (str+i));
-
if(new[strlen(new)-1] == '"') {
-
new[strlen(new)-1] = '\0';
-
return new;
-
} else {
-
return NULL;
-
}
-
} else
-
return NULL;
-
}
Then the code is more compact and uses the built in functions (smart :). But I'm still not getting proper output... I think it might be the input that's not proper :s
This is my testcase which makes it fail: - #include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
char * prepareMessage(char str[]) {
-
int i=0, j=0, state=0;
-
char * new;
-
-
char * pMsgStart = strstr(str, "new ");
-
if(pMsgStart!=NULL) {
-
int i = (strstr(str, "new ")-&str[0])+5;
-
new = malloc(strlen(str)-i);
-
strcpy(new, (str+i));
-
if(new[strlen(new)-1] == '"') {
-
new[strlen(new)-1] = '\0';
-
return new;
-
} else {
-
return NULL;
-
}
-
} else
-
return NULL;
-
}
-
-
int main() {
-
char inputBuffer[200];
-
-
do {
-
if(fgets(inputBuffer, 200, stdin)==0) {
-
strcpy(inputBuffer,"exit");
-
} else {
-
char * new = prepareMessage(inputBuffer);
-
printf("%s\n",new);
-
free(new);
-
}
-
} while (strcmp ("Apple",inputBuffer) != 0);
-
-
-
return 0;
-
}
K
JosAH 11,448
Recognized Expert MVP
You should malloc at least one byte more on line #12; the \0 character needs to
be stored as well.
kind regards,
Jos
JosAH 11,448
Recognized Expert MVP
ps. oh, and btw, the fgets() function also returns the end-of-line character(s) in
the buffer so the last character can never be a double quote in your buffer.
kind regards,
Jos
You should malloc at least one byte more on line #12; the \0 character needs to
be stored as well.
Ok. But it's not much use if nothing is returned... It's something with the fgets i think... If I use a plain array like this: -
char inputBuffer[200] = "new \"message\"";
-
char * new prepareMessage(inputBuffer);
-
it works, but the value comes from fgets() like this: - char inputBuffer[200] = "";
-
char * tmp = malloc(200);
-
-
do {
-
if(fgets(tmp, 200, stdin)==0) {
-
strcpy(inputBuffer,"exit");
-
} else {
-
strcpy(inputBuffer, tmp);
-
char * new = prepareMessage(inputBuffer);
-
printf("%s\n",new);
-
free(new);
-
}
-
} while (strcmp ("Apple",inputBuffer) != 0);
it's not working... Why!?
it's not working... Why!?
I still don't know why, but this code seems to be working. Not 100% shure, but it gives me the right string every time :) - #include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
char * prepareMessage(char str[]) {
-
int i=0, j=0, state=0;
-
char * new;
-
-
char * pMsgStart = strstr(str, "new ");
-
if(pMsgStart!=NULL) {
-
int i = (strstr(str, "new ")-&str[0])+5;
-
new = malloc(strlen(str)-i+1);
-
strcpy(new, (str+i));
-
if(new[strlen(new)-2] == '"') {
-
new[strlen(new)-2] = '\0';
-
return new;
-
} else {
-
return NULL;
-
}
-
} else {
-
return NULL;
-
}
-
}
-
-
int main() {
-
char inputBuffer[200] = "";
-
char * tmp = malloc(200);
-
-
do {
-
if(fgets(tmp, 200, stdin)==0) {
-
strcpy(inputBuffer,"exit");
-
} else {
-
strcpy(inputBuffer, tmp);
-
char * new = prepareMessage(inputBuffer);
-
printf("%s (%d chars long)\n",new, strlen(new));
-
free(new);
-
}
-
} while (strcmp ("Apple",inputBuffer) != 0);
-
-
return 0;
-
}
-
-
JosAH 11,448
Recognized Expert MVP
it's not working... Why!?
Read my reply #5.
kind regards,
Jos
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: mosfets |
last post by:
Hi,
I'm having a little trouble figuring out the difference in terms of
memory allocation between:
class person_info;
class A {
private:
|
by: Guha |
last post by:
I have a problem with returning a 2D array using a function which is
called in main(). The piece of the code is given below. This is a test
code only.
#include"stdio.h"
#include"alloc.h"
...
|
by: shan |
last post by:
How to return an two dimensional array in user defined function to main
function.
I think it is posible by using pointers but don't know how to code.or
is there any method without using...
|
by: enki |
last post by:
What I want to do is create sprites and put them in a vector. I know
that this specific example dosn't realy fit in this group but my sprite
are ponters.
vector<*sprite>spvec;
sprite *...
|
by: Bhan |
last post by:
Hi,
Can I get answers for the following:
1. Usage of Double Pointers during allocation memory.Heard that if
memory is to be allocated by someone who is working on another
module,then we...
| |
by: Martin Jørgensen |
last post by:
Hi,
I'm relatively new with C-programming and even though I've read about
pointers and arrays many times, it's a topic that is a little confusing
to me - at least at this moment:
----
1)...
|
by: MotoK |
last post by:
Hi Experts,
I've just joined this group and want to know something:
Is there something similar to smart pointers in C or something to
prevent memory leakages in C programs.
Regards
MotoK
|
by: MC felon |
last post by:
how do we return strings or arrays from a function? i tried..
char some_func() //where i thought char would tell the compiler
that the return is a string
{
char str;
//something;
return...
|
by: J Caesar |
last post by:
In C you can compare two pointers, p<q, as long as they come from the
same array or the same malloc()ated block. Otherwise you can't.
What I'd like to do is write a function
int comparable(void...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...
| |