Reputation:
I have an array of pointers to arrays, in a function. I need to access that array in another function.
Pointer array
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 the other 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"
the output of otherfunction();
is:
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) whats going wrong here. (1) How do i fix it (2) Or is there a better way to do this. the requirements are otherfunction()
cant take any arguments and ptr
needs to remain local to its function. (Im certain the other code is not contributing to the problem and nothing is wrong with ptr
)
Upvotes: 0
Views: 2505
Reputation: 213809
(0) whats going wrong here. (1) How do i fix it (2) Or is there a better way to do this
(0) The whole program design. Using global variables like this - pointers in particular - is one form of spaghetti programming and should be avoided. You are creating tight couplings and dependencies between all kinds of unrelated parts in your program.
In general, the presence of pointer-to-pointers is usually an indication of poor design. Pointer-to-pointers have a few valid uses, for special cases such as returning a modified pointer through a function parameter. There is no apparent reason to use them in your case.
(1) By using a couple of type qualifiers and storage specifiers to reduce scope of those messy, global variables. Instead, access the pointer array through setter/getter functions.
(2) Yes, change the 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;
}
Upvotes: 1
Reputation: 29332
char *ptr[size + 1];
char* p = *ptr;
char* str = &p[n];
This makes p point to the first string of the ptr
array of strings, and then str
will iterate over that string character by character. I think that what you meant to do is this:
char** p = ptr; // p points to the first string of ptr
...
char* str = p[n]; // str points to the nth string of ptr
Apart of that, using global pointers is not a good idea. Possibly better is to pass ptr
itself to the function otherFunction
, which would have the protoype:
void otherFunction(char** p);
and you call it with ptr
:
otherFunction(ptr);
Upvotes: 2
Reputation: 26717
ptr
is an array of pointer.
char **p = ptr;
char *str = p[n];
printf("%i %s\n", n, str);
Upvotes: 3