0

I am trying to retain the value of array1_ptr[i] between the calls in different files i.e. test.c and testfunc.c. But it is not retaining the value in next call

file: test.h

extern char** array1_ptr;

void change_ptr1(int i); //to fill the values in array1_ptr
void memalloc();

file: test.c

#include "test.h"
char** array1_ptr;
int main()
{   
    int i;
    memalloc();
    for(i = 0; i < 10; i++)
    {
        change_ptr1(i);//calling the function whose definition in other file
    }
    return 0;
}

file: testfunc.c

#include "test.h"

void change_ptr1(int i)
{
    array1_ptr[i] = i + 1; //filling the values which are not retained in next call
}
void memalloc()
{
    int i;
    array1_ptr = (char**)malloc(10 * sizeof(char*));
    for(i = 0; i < 10; i++)
        array1_ptr[i] = (char*)malloc(10 * sizeof(char));
}
debugger
  • 31
  • 3
  • "Next call"? You call it only once (for each `i`)... – glglgl Nov 07 '13 at 08:46
  • 2
    A 2D array and a pointer to a pointer are two very different things. The first is 100 chars and no pointers, the second is 10 pointers, each pointing to 10 chars. – ugoren Nov 07 '13 at 08:50
  • Sense - this makes none. In `change_ptr1` you take double pointer, dereference it once (via `[]`) end up with a pointer to which you try to assign a value. Anyway, what is the question? – friendzis Nov 07 '13 at 09:00
  • I want to store some values in the ten different pointers declared in the code – debugger Nov 07 '13 at 09:05
  • There aren't 10 pointers that I can see in this code. I see one 2D array, one pointer-to-pointer, and a *whole lotta **undefined behavior***. And in case it hasn't been hammered home, they're not even *close* to compatible. The only thing they share is syntactic sugar. And if this: `char** array1_ptr = array1;` doesn't fill your compile-log with warnings,your warning level isn't high enough. – WhozCraig Nov 07 '13 at 09:35
  • 1
    [Please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169) (he said, hoarsely). – unwind Nov 07 '13 at 11:23

0 Answers0