I'm filling a stringtable char* data [500] with pointers to different strings.
char* data [500];
int stringC = 0;
char PrintBuffer[200];
void data_display(void);
void printStringTable(void);
int main() {
data_display(); //fill buffer
printStringTable();
return 0;
}
Here i use another Buffer so that i can store an Index in the String:
void data_display(void)
{
int index =0;
sprintf(PrintBuffer,"A Text %d\n", index);
output(PrintBuffer);
index ++;
sprintf(PrintBuffer,"B Text %d\n",index);
output(PrintBuffer);
index ++;
sprintf(PrintBuffer,"C Text %d\n",index);
output(PrintBuffer);
}
When debugging I can see that the pointer always points to the same adress.
void output(char* Buffer)
{
data[stringC]= Buffer;
char*(*ptr)[500] = &data;
stringC++;
ptr+=stringC;
}
void printStringTable()
{
int i;
for (i = 0; i < 3; i++) {
printf(data[i]);
}
}
If I have pure strings without using another Buffer (PrintBuffer) every pointer points to a different adress and I get:
A Text 0 B Text 1 C Text 2
But in this constellation I get:
C Text 2 C Text 2 C Text 2
Is there a way to increment the pointer so that it points to a different adress?
All pointers in the data
array point to the same location, that is PrintBuffer
.
You must allocate a new buffer for each of your strings.
The output function shoukd be modified like this:
void output(char* Buffer)
{
char *newbuffer = strdup(Buffer) ;
data[stringC]= newBuffer;
// removed: this it's pointless char*(*ptr)[500] = &data;
stringC++;
// removed: this it's pointless ptr+=stringC;
}