I'm a noob to C and I found my program acting very weird:
Here's the code:
#include <stdbool.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>
char * p(char arg[] , char sym[] , int i , bool rv) {
char head[i],w[i];
strncpy(head,arg,i); head[i] = "\0";
int l;
for (l = 0 ; l <= (int)(strlen(sym) / i) ; l++) {
strncpy(w,sym+l*i,i); w[i] = "\0";
if (strcmp(head,w) == 0) {
if (rv) { return head; } else {
char v[strlen(arg) - i];
strcpy(v,arg+i);
v[strlen(arg)-i] = "\0";
return v;
};
};
};
return arg;
}
int main() {
printf(p("/parameter","+-\\/",1,false));
getch();
}
The MAIN problem is that the returning value of the function is either a "string" of randomly generated codes or simply nothing.
It was expected to return /
for return h;
and parameter
for return v;
.
The other problem is that there is NO error found when I compile the program but bunch of warnings telling that the function returns address of local variable
and assignment makes integer from pointer without a cast
.
In the other hand, return arg;
in very peaceful and doesn't gives out any error. (Try to change my codes in p("/parameter","+-\\/",1,false)
if you don't believe it.) What have I done wrong?
Usage of the function:
p("argument_passed_to_check","symbols_accepted to_be_at_the_front","separate_for_each_
i
_characters","return_header_instead_of_parameter")
expected result:
p("-argue","/\\-",1,false)
returns argue
p("/help","me",1,false)
returns /help
p("/help","me",1,true)
returns (null)
p("--parameter","--++",2,false)
returns parameter
p("--parameter","--++",2,true)
returns --
Summary for what am I asking help for:
Except for
return arg
, other returning parts is weird:return head;
is giving out random characters ;return v;
returns nothing at all. How can I let them work as the expected results?Why are there those warnings?