I am currently trying to make a c function to transform a string into an n*n matrix made from the ascii value of the characters of the string.For example the string "Wordsss" should give a matrix such as
87 111 82
100 115 115
115 0 0
The space between the differents values should be tabulations. My current code is :
int matrix_size(int length)
{
int n = 0;
double square = sqrt(length);
if ((int)square % 1 != 0 ){
n = ((square / 1) - ((int)square % 1)) + 1;
length = n;
} else {
n = square + 1;
length = n;
}
}
int key_matrix(int ac, char **av)
{
int length = strlen(av[2]);
int i = 0;
int j = 0;
int n = matrix_size(length);
int limit = pow(n, 2);
while(i < limit){
if(i % n == 0 && i != 0){
printf("%d\n", av[2][i]);
++i;
} else if (i > length && i < limit){
printf("%d\t", 2);
} else {
printf("%d\t", av[2][i]);
++i;
}
}
}
There are a whole bunch of issues here.
int
but do not have a return. In the case of key_matrix
it appears the correct return type should be void
since this function appears designed only to print output.(int)square % 1 != 0
is always true.matrix_size
the last action you take is to assign to length
, but as length is a local variable (an argument) this has no effect. You may be thinking this will modify the argument passed in, but to do that you'd have to pass a pointer, then assign to that memory location.av
in int length = strlen(av[2]);
without checking that the array contains that many strings. Presumably ac
contains this information. It's unclear why the third string in the array is important.If I want to get the size of the output matrix based on the length of the string, I'll find the floor of the square root. If multiplying that my itself yields the original length, it's fine as-is. This covers numbers like 9 or 16. Otherwise, it'll return that number plus one.
This neatly handles cases where floating point math says the square root of something like 10000 is 99.999999... rather than 100.
size_t matrix_dimension(size_t length) {
size_t s = floor(sqrt((double)length));
if (s * s == length) {
return s;
}
else {
return s + 1;
}
}
Now, I'll write a function to print a "matrix" for one string. If we need to handle multiples, we can simply write a loop and call this function multiple times.
Note that I use a width specifier on my format specifier to achieve tabulation rather than tabs.
void print_matrix(char *str) {
size_t slen = strlen(str);
size_t len = matrix_dimension(slen);
for (size_t i = 0; i < len; i++) {
for (size_t j = 0; j < len; j++) {
size_t k = i * len + j;
if (k >= slen) {
printf("%4d", 0);
}
else {
printf("%4d", (int)str[k]);
}
}
printf("\n");
}
}