I have the below function which when called from main, returns a formatted filename (000.jpg) as a string when given an int. (I know we can use sprintf for this)
Initialising char fn[8] = "000.jpg"
in main works.
When passed into function getfilename()
,
assigning indiv chars e.g. fn[4] = 'p';
works,
but it won't work if I assign fn = "000.gif";
I get a Bus error: 10
What am I doing wrong?
(The rest of the code works fine, and output is correct so long as I don't do the line: fn = "000.gif";
But I want to learn how to be able to manipulate the string when passed across functions)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *getfilename(int counter, char *fn);
int main(void) {
int counter=14;
char fn[8]= "000.jpg"; // this is fine
getfilename(counter, fn);
printf("%s\n", fn);
}
char *getfilename(int counter, char *fn) {
fn[7] = '\0';
fn[4] = 'p'; // this is fine
fn[5] = 'n';
fn[6] = 'g';
//fn = "000.gif"; // this will return Bus error: 10
// ITOA IMPLEMENTATION FOR 3-DIGIT FILENAME
int numOfDigits = log10(counter) + 1;
for (int i=numOfDigits-1; i>=0; i--, counter/=10) {
if (numOfDigits==1) {
fn[i+2] = (counter % 10) + '0';
fn[0] = fn[1] = '0';
}
else if (numOfDigits==2) {
fn[i+1] = (counter % 10) + '0';
fn[0] = '0';
}
else {
fn[i] = (counter % 10) + '0';
}
}
//////////
return fn;
}