I am writing a function, which takes some char array as an input from the main()
. This function returns pointer to char. There are three problems:
main()
needs to be able to access this subarray, I can use malloc
in the function to create this global subarray. {}
to main()
. NULL
pointer. I only have question about the second issue. How do I pass pointer to the empty character array {}
to the main()
? I don't know if malloc
will be helpful here.
**EDIT**
:
Ok, I think I caused some confusion. Let me specify the exact problem. I am writing a function of the form char * test(char * a, int start, int end, int len)
. Now a typical input to this would be an array like {'a', 'b', 'c'}
for the array, start = 0
, end = 3
, len = 3
. len
here is the length of the input array. start
is the starting position. In this example, its 0
, which is beginning of the array. Now the end
value says that start at the start
value and take end
no of elements from the start
value. In this example, it will mean , start at 'a'
and take 3 elements from there, ie 'a'
, 'b'
, and 'c'
. And form a new array with such a selection. Here we get original array back. So let a[] = {'a', 'b', 'c'}
. Then test(a , 0 , 3 , 3)
will return a pointer to {'a', 'b', 'c'}
. Likewise, test(a , 0 , 2 , 3)
will return a pointer to {'a', 'b'}
and test(a , 1 , 2 , 3)
will return a pointer to {'b', 'c'}
. Now I want the function to return a NULL
pointer if (start < 0) || (end < 0) || (0 == len) || (start+ end > len)
(start < 0) || (end < 0) || (0 == len) || (start+ end > len)
(start < 0) || (end < 0) || (0 == len) || (start+ end > len)
. So in the following situations the function returns a NULL
pointer. test(a , 0 , 4 , 3)
test(a , 1 , 3 , 3)
test(a , 2 , 2 , 3)
test(a , 3 , 1 , 3)
test(a , -1 , 2 , 3)
test(a , -1 , -2 , 3)
and if a[] = {}
then test(a , 0 , 1 , 3)
should return NULL
. I got this figured. Now if the end
value is 0
, I want to function to return the pointer to the empty array {}
. Function should not modify the original array.
EDIT NO 2:
I am doing sample problem 3 from http://admin.cs.mum.edu/Pretest/sampletest.htm . Hope that helps...
You can return structure which will contain the pointer to the address & length which will be filled inside your function.
struct ret_me
{
char *p;
int len;
}
.....
main()
{
.......
struct ret_me xxx;
xxx=your_fun(...);
if(xxx.len == 0)
...array is empty...
..........
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.