Global pointer to local pointer array
I have an array of pointers to arrays in a function. I need to access this array in another function.
Pointer mask
char *ptr[size + 1];
I made a global pointer
char *p;
which I pointed to ptr (in the same function as ptr)
p = *ptr;
then i tried to access ptr from another function
void otherFunction(void){
for(int n = 0; n < 6; n++)
{
char* str = &p[n];
printf("%i %s\n", n, str);
}
}
when
ptr[0] = "abcd"
ptr[1] = "bcde"
ptr[2] = "cdef"
ptr[3] = "defg"
ptr[4] = "efgh"
ptr[5] = "fghi"
conclusion otherfunction();
:
0 abcd
1 bcd
2 cd
3 d
4
5
I want the output to be
0 abcd
1 bcde
2 cdef
3 defg
4 efgh
5 fghi
My questions are: (0) What is wrong here. (1) How to fix this? (2) Or is there a better way to do it. requirements otherfunction()
cannot accept any arguments, but ptr
must remain local to its function. (I'm sure the other code doesn't affect the problem, and nothing works with ptr
)
char *ptr[size + 1];
char* p = *ptr;
char* str = &p[n];
This makes p a point for the first line of the string array ptr
, and then str
iterates over that string character by character. I think you wanted to do this:
char** p = ptr; // p points to the first string of ptr
...
char* str = p[n]; // str points to the nth string of ptr
Also, using globals is not a good idea. It's probably best to pass ptr
yourself to a function otherFunction
that would have a protoype:
void otherFunction(char** p);
and you call it with ptr
:
otherFunction(ptr);
source to share
(0) what's going wrong here. (1) How to fix it (2) Or is there a better way to do it
(0) The entire design of the program. Using global variables such as pointers in particular is a form of spaghetti programming and should be avoided. You create hard links and dependencies between all kinds of unrelated parts in your program.
In general, having pointers to pointers is usually an indicator of poor design. Pointers have several valid uses for special cases, such as returning a modified pointer through a function parameter. There is no obvious reason to use them in your case.
(1) Using multiple type specifiers and storage specifiers to reduce the size of these messy globals. Instead, access the array of pointers via setter / getter functions.
(2) Yes, change your program to something like the code below:
static const char* ptr [] =
{
"abcd",
"bcde",
"cdef",
"defg",
"efgh",
"fghi",
NULL
};
inline const char* get_str (size_t index)
{
return ptr[index];
}
inline void set_str (size_t index, const char* str)
{
ptr[index] = str;
}
source to share