Concatenating uint8_t to a char* - c

im really new to C and im having a bit of a complication creating a char* from various uint8_t
My idea is to create a char* where in each location I place a number form a matrix
For example if I have a matrix with:
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
id like a char* thats "01234567890123456"
what im doing bit its not working is:
char* string = malloc(sizeof(char)*matrix->height*matrix->width);
for (int i = 0; i < matrix->height ; ++i) {
for (int j = 0; j < matrix->width ; ++j) {
string[i*matrix->height+j] = matrix->value[i][j];
}
}
of course its not working but im a bit lost on how to proceed and I cant find more information regarding this problem.
Any help would be nice,
thanks

Since you're trying to print a string, you need the ASCII character for 0. So, simply add '0' to each number, like so
char* string = malloc(sizeof(char)*(matrix->height*matrix->width + 1));
for (int i = 0; i < matrix->height ; ++i) {
for (int j = 0; j < matrix->width ; ++j) {
string[i*matrix->width+j] = matrix->value[i][j] + '0';
}
}
string[matrix->height*matrix->width] = 0; //null terminator
Note however this isn't exactly the most portable solution.
Also, notice that you want to multiply i by the width, because if you didn't have a square matrix your calculation wouldn't work correctly.
It's kind of unnecessary to have sizeof(char), because the size of a char is defined to be 1 regardless of the byte size.

Related

segmentation fault (core dumped) error when trying to copy from an array

trying to copy stuff from b into a but i get that error
someone told me it means i'm trying to access memory that i'm not allowed to, but i don't know what should i do to make it compile.
replace(txt , code);
string replace(string a , string b)
{
string alpha[26] = {"abcdefghijklmnopqurstuvwxyz"};
for (int i = 0; i < strlen(a); i++)
{
for(int n = 0; n < 26; n++)
{
if(a[i] == alpha[n])
{
a[i] = b[n];
i++;
}
}
}
return word;
}
i'm a beginner so no comments about clean coding or syntactic sugar or stuff like that just help me resolve this please
It looks like you have some problems with understending pointers, so I recommend you to read about them. Also consider reading about datatypes and types from STL you are using. (cause std::string is already an array of values so, when you are creating std::string[26], you actually are creating pointer to a pointer)
I guess you have are trying to do something like that:
std::string replace(string a , string b)
{
std::string alpha = {"abcdefghijklmnopqurstuvwxyz"};
for (size_t i = 0; i < a.size(); ++i)
{
for(size_t n = 0; n < alpha.size(); ++n)
{
if(a[i] == alpha[n])
{
a[i] = b[n];
i++; // Also, I think you doesnt need this line, cause you already incrementing i in for loop
}
}
}
return a;
}
Also you have used strlen() on your string, that also is not really correct, cause it is used on char values. If you whant to get length of a string it is better to use string.lenght()
Also, It is better to use size_t or unsigned int instead of int in this case, cause you don't need negative numbers in order to parce these strings. ()

How to add space between every characters using C

I want a space between every character of a string like I will give input "HELLO"
the result will be "H E L L O"
I need help in that
[Edit from comments]
I want it in a string
for (i = 0; i <= strlen(str); i++) {
printf("\n String is: %s", str[i]);
printf(" ");
}
The shorter, more general answer is that you need to bump characters back, and insert a ' ' in between them. What have you done so far? Does it need to be in place?
One (perhaps not optimal, but easy to follow solution) would be making a larger array, copying in alternating letters, something like (not guaranteed to work verbatim)
char foo[N]; // assuming this has N characters and you want to add a space in between all of them.
char bar[2*N];
for (int i = 0; i < N; i++) {
bar[2*i] = foo[i];
if (i != N - 1)
bar[2*i + 1] = ' ';
}
Of course, this new string is in bar, but functions as desired. At what point are you having issues?
try this
#include <stdio.h>
void add_spaces(char need_to_add[])
{
int len = strlen(need_to_add);
char with_spaces[len*2];
int space_index = 0;
for (int i=0 ; i<len ; i++)
{
with_spaces[space_index]=need_to_add[i];
with_spaces[++space_index]=' ';
space_index=space_index+1;
}
printf("%s\n", with_spaces);
}
int main()
{
char * a = "aaa";
add_spaces(a); // fraught with problems
return 1;
}

realloc() seems to affect already allocated memory

I am experiencing an issue where the invocation of realloc seems to modify the contents of another string, keyfile.
It's supposed to run through a null-terminated char* (keyfile), which contains just above 500 characters. The problem, however, is that the reallocation I perform in the while-loop seems to modify the contents of the keyfile.
I tried removing the dynamic reallocation with realloc and instead initialize the pointers in the for-loop with a size of 200*sizeof(int) instead. The problem remains, the keyfile string is modified during the (re)allocation of memory, and I have no idea why. I have confirmed this by printing the keyfile-string before and after both the malloc and realloc statements.
Note: The keyfile only contains the characters a-z, no digits, spaces, linebreaks or uppercase. Only a text of 26, lowercase letters.
int **getCharMap(const char *keyfile) {
char *alphabet = "abcdefghijklmnopqrstuvwxyz";
int **charmap = malloc(26*sizeof(int));
for (int i = 0; i < 26; i++) {
charmap[(int) alphabet[i]] = malloc(sizeof(int));
charmap[(int) alphabet[i]][0] = 0; // place a counter at index 0
}
int letter;
int count = 0;
unsigned char c = keyfile[count];
while (c != '\0') {
int arr_count = charmap[c][0];
arr_count++;
charmap[c] = realloc(charmap[c], (arr_count+1)*sizeof(int));
charmap[c][0] = arr_count;
charmap[c][arr_count] = count;
c = keyfile[++count];
}
// Just inspecting the results for debugging
printf("\nCHARMAP\n");
for (int i = 0; i < 26; i++) {
letter = (int) alphabet[i];
printf("%c: ", (char) letter);
int count = charmap[letter][0];
printf("%d", charmap[letter][0]);
if (count > 0) {
for (int j = 1; j < count+1; j++) {
printf(",%d", charmap[letter][j]);
}
}
printf("\n");
}
exit(0);
return charmap;
}
charmap[(int) alphabet[i]] = malloc(sizeof(int));
charmap[(int) alphabet[i]][0] = 0; // place a counter at index 0
You are writing beyond the end of your charmap array. So, you are invoking undefined behaviour and it's not surprising that you are seeing weird effects.
You are using the character codes as an index into the array, but they do not start at 0! They start at whatever the ASCII code for a is.
You should use alphabet[i] - 'a' as your array index.
The following piece of code is a source of troubles:
int **charmap = malloc(26*sizeof(int));
for (int i = 0; i < 26; i++)
charmap[...] = ...;
If sizeof(int) < sizeof(int*), then it will be performing illegal memory access operations.
For example, on 64-bit platforms, the case is usually sizeof(int) == 4 < 8 == sizeof(int*).
Under that scenario, by writing into charmap[13...25], you will be accessing unallocated memory.
Change this:
int **charmap = malloc(26*sizeof(int));
To this:
int **charmap = malloc(26*sizeof(int*));

How cast array[4] to array[2][2]?

I have a array short frame[4] and I want it as a function parameter as short frame[2][2]
How can I cast it? I tried different things (like *(short [2][2])&frame[0]*), but I still get error messages.
Also not working is if I declare the function with void function(short frame[2][2])
and call the function with function(&frame[0]) while frame is a short frame[4];
I don't think it is a good pratice, anyway:
f((short (*)[2])a);
This works here, albeit with a warning.
#include <stdio.h>
void function(short frame[2][2])
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
printf("%d ", frame[i][j]);
printf("\n");
}
int main()
{
short frame[4] = { 0, 1, 2, 3 };
function(&frame[0]);
return 0;
}
What error message do you get?
You can't cast between different dimensional arrays.
It wouldn't know which way round you wanted it.
You'll have to write a function.
In pseudocode:
function castArray(short[4] input){
short[2][2] output = new short[2][2];
output[0][0] = input[0];
output[0][1] = input[1];
output[1][0] = input[2];
output[1][1] = input[3];
return output;
}
You achieve it an easy way like this :
Converting 1-D array into 2-D array
short frame[MAX];
short dup_frame[ROW][COL];
int i,j,k;
for(i = 0 ; i < MAX ; i++)
{
j= i / ROW ; // you can do it by i / COL also
k= i % ROW ; // you can do it by i % COL also
dup_frame[j][k] = frame[i];
}

is there a function that lets me look at the next char?

is there a function in c that lets me look at the next char in an array? Also where could I find this information on my own, I tried Google and looking for existing threads on this site.
I am trying to pull numbers from a line, and store those numbers. So I want to do something like
if(c = a number and c "next character" is not a number){value is = value*10+c-'0', store number}
If the current character is array[i], the next character is array[i+1].
You could write a method to do this:
char next_char(char *array, int i, int size){
return (++i) < size ? array[i] : '\0';
}
EDIT: After reading your question something like this may be reasonable.
if(isdigit(array[i]) && !isdigit(next_char(array,i,size)){
..
}
A better solution would be a for loop:
int val = 0;
for(i = 0; i < size; i++){
if(isdigit(i)){
val = 10 * val + array[i] - '0';
}else{
// Store the value
val = 0;
}
}
To get a char from a char array, you just use:
array[i]
where is is an index.
If you want to read every char, you can use a loop:
for(size_t i = 0; i < sizeof(array); i++)
{
char cur = array[i];
}
You could also increment a pointer.

Resources