I am writing a C program. I have a data structure called MyStruct that contains a character pointer and also an integer field. I have an array of MyStruct called myArray. What I need is to simply initialize this array by MyStructure structs by initiateParams() function and then read the values of myArray and display them on screen by displayParams().
The initiateParams() function just initializes integer and char* fields of variables of class MyStruct by incrementing integers. After initialization, when I want to retrieve values by displayParams() the value of integer field (intigerData) is retreived correctly; but the value of pointer field (characterSet) displayed incorrectly; maybe the value of last char* value assigned to the last structure. How can I retrieve pointer values correctly? Thank you.
#include <stdio.h>
#include <stdlib.h>
//#include"structHeader.h"
#include <stdint.h>
void initiateParams();
void displayParams();
char* itoa(int value, char* result, int base);
typedef struct _MyStruct
{
char* characterSet;
uint16_t intigerData;
uint16_t * intigerDataPtr;
} MyStruct;
const uint16_t bufferSize = 400;
MyStruct myArray[400];
int main ()
{ initiateParams();
displayParams();
printf("ended");
return 0;
}
void initiateParams(){
uint16_t i;
for(i = 0 ; i < 4*bufferSize ; i++){
uint16_t k = i % bufferSize;
MyStruct myStruct;
myStruct.intigerData = i;
char c;
char* c2 = itoa(i , &c , 10);
c = *c2;
myStruct.characterSet = &c;
myStruct.intigerDataPtr = & i;
//printf("%s\r\n" , &dig);
myArray[k] = myStruct;
}
}
void displayParams(){
uint16_t i;
for(i = 0 ; i < bufferSize ; i++){
MyStruct api = myArray[i];
printf("retrieved integer value: %d , character pointer value: %s\r\n"
, api.intigerData , api.characterSet);
printf("%s\r\n" , api.characterSet);
}
}
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"
[35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
This line
only stores a pointer to the temporary variable ‘c’ which is allocated on the stack.
You should at least store the value of ‘c2’ variable (without ‘*’) in the characterSet field.
Also you are not allocating the buffer, passing &c to itoa is erroneous.
You should (for each character) allocate the buffer:
and deallocate the structure when you’re done (after displayParams).
The code should be