I am working on some simple string related code(I am beginner in this), when I execute this code I get a warning that I don't understand. this is the code.
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE sizeof(double) + sizeof(Extension) + 2
char* buffer[LOG_MIN_FILENAME_SIZE];
int timez = 0;
int minutes = 0;
int main()
{
char _acBuff[LOG_MIN_FILENAME_SIZE];
char* ListOfFiles[14];
for(int i=0; i<14; i++){
sprintf(_acBuff, "%d" "%d"Extension, timez, minutes);
ListOfFiles[i]= _acBuff;
}
for(int i=0; i<14; i++){
sprintf(buffer, "%s", ListOfFiles[i]);
printf("%s", buffer);}
}
and this is the warning:
warning: Format "%s" expects Arguments of type char* but Argument 2 has type "char**"
to my understanding I used the correct Format specifier so what exactly is the issue?
You want this:
#include <stdio.h>
#include <stdlib.h> // needed for malloc
#include <string.h> // needed for strcpy
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE sizeof(double) + sizeof(Extension) + 2
char buffer[LOG_MIN_FILENAME_SIZE]; // you want an array of char, not an array of
// pointers to char
int timez = 0;
int minutes = 0;
int main()
{
char _acBuff[LOG_MIN_FILENAME_SIZE];
char* ListOfFiles[14];
for (int i = 0; i < 14; i++) {
sprintf(_acBuff, "%d" "%d"Extension, timez, minutes);
ListOfFiles[i] = malloc(strlen(_acBuff) + 1); // allocate memory for the string
strcpy(ListOfFiles[i], _acBuff); // copy the string
// your code only copies the same
// pointer over and over
}
for (int i = 0; i < 14; i++) {
sprintf(buffer, "%s", ListOfFiles[i]);
printf("%s\n", buffer); // added a \n, so output is readable
}
}
Disclaimers:
sizeof(double)
is still wrong here, but doesn't have any consequences. You should find out yourself why.