I am trying to write a program which dynamically allocates memory for a certain string, and then i want to store 5 different values of the same string within the memory so i can access it later. Some of the code ive written is
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
int main( int argc, char *argv[] )
{
int c;
int i = 0;
int k = 0;
int d = 43;
char *data = (char*) malloc(5 * 40 * sizeof(int));
char buf[40];
while (i<5){
time_t t = time(NULL);
struct tm tm = *localtime(&t);
//printf("%d-d-d d:d:d ",tm.tm_mon 1, tm.tm_mday,tm.tm_year 1900, tm.tm_hour, tm.tm_min, tm.tm_sec); // 28
//printf("%ld\n",sizeof("%d-d-d d:d:d"));
//printf("%d: %f\n", d, d/58.0 ); // 8
sprintf(buf,"%d-d-d d:d:d %d: %f\n", tm.tm_mon 1, tm.tm_mday,tm.tm_year 1900, tm.tm_hour, tm.tm_min, tm.tm_sec,d, d/58.0);
//printf("%ld\n",sizeof("%d: %f\n"));
if (k < (5*40)){
int j = 0;
while (j<40){
*(data j k) = buf[j];
j ;
}
k =40;
}
printf("%s",data);
i ;
sleep(1);
}
printf("Finished");
// printf("%d",*(data));
}
So, at each iteration of the loop the 'buf' variable stores a different datetime and then i copy it to the allocated memory. So in theory, i have 5 different datetime buffer stored in the allocated memory. When i continue with the compilation of this code,data only prints one datetime and not the rest. If im understanding it correctly, its because im only accessing the first memory location? Am i doing something wrong? If so, how would i go about storing 5 different date time strings and then accessing them all
CodePudding user response:
Assuming you don't know the individual string lengths until run-time, then you'd allocate this as char* data[5];
and assign each data[i]
to point at malloc(strlen(some_string) 1)
. Then strcpy
into this allocated space. You'll need a free()
call per malloc
call.
Or if you for some strange reason just want to dynamically allocate a 2D array with dimensions 5x40, then that would be:
char (*data)[40] = malloc( sizeof(char[5][40]) );
...
data[i][j] = some_character;
...
free(data);