Put value into char 2D array - c

I try to put value of two integers into char array.
If I have:
x = 3;
y = 5;
then I want to have
links[0][0] = "3,5";
I have this code now, but I don't know how can I continue.
char** links = (char**) calloc(SRTM_SIZE, sizeof(char*));
if(links)
{
for(int i = 0; i < SRTM_SIZE; i++)
{
links[i] = (char*)calloc(SRTM_SIZE, sizeof(char));
//memset(links[i], 0, sizeof(*links[i] * SRTM_SIZE));
}
}
x = strtok(temp, ",");
y = strtok(NULL, ",");
int xx = atoi(x);
int yy = atoi(y);
//Some calculation with x and y and if it's okay, then I need to put value of x and y to array, but I don't know how
printf("%s\n", links[0][0]);
edited:
What exactly I need is matrix (propably 1201x1201) of strings. Into cells (not into all, but propably into most of them) I need put string values. This values can be from "0,0" to "1200, 1200". And later in program I need to acces to all cells with strings values, because each value is position of one of adjacent cells.

use sprintf
sprintf(links[0][0],"%d,%d",x,y);
but before change links[0][0] to string(char*)
"3,5" is string not a character.
more info http://www.cplusplus.com/reference/cstdio/sprintf/

links[0][0] is of single byte. You can store only 1 byte to it ,i.e, a single character. These two characters would store into the two different memory location, say, link[0][0] and link[0][1]. Then you also need a \0 character to use %s to print them.
The statement
printf("%s\n", links[0][0]);
is wrong %s is used for strings but links[0][0] is a char.
You can do this as
sprintf(links[0], "%d,%d", xx,yy);
printf("%s\n", links[0]);
Test code after changes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SRTM_SIZE 5
int main(void){
char** links = (char**) calloc(SRTM_SIZE, sizeof(char*));
if(links)
{
for(int i = 0; i < SRTM_SIZE; i++)
{
links[i] = (char*)calloc(SRTM_SIZE, sizeof(char));
//memset(links[i], 0, sizeof(*links[i] * SRTM_SIZE));
}
}
char temp[5]="2,3";
char *x = strtok(temp, ","); //strtok() returns pointer to char.
char *y = strtok(NULL, ",");
int xx = atoi(x);
int yy = atoi(y);
sprintf(links[0], "%d,%d", xx,yy);
//Some calculation with x and y and if it's okay, then I need to put value of x and y to array, but I don't know how
printf("%s\n", links[0]);
}

#include <stdio.h>
#include <stdlib.h>
int main(void){
int len;
int x = 3, y = 5;
len = snprintf(NULL, 0, "%d,%d", x, y);
char *link = malloc(len + 1);
sprintf(link, "%d,%d", x, y);
printf("%s\n", link);
free(link);
return 0;
}

You can't assign a value to a 2D array the way you do it. This is how it works:
arr[0][0]= x;
arr[0][0] refers to a single location, that is row 0, and column 0.
If you have arr[2][2], you will have to specify where you want to put your value in the 2D array. If you want it in the first row, at the last column:
arr[0][2]= x;
You may visualize a 2D array as follows:
int arr[3][2]:
column 0 column 1
row 0 |arr[0][0]| |arr[0][1]|
row 1 |arr[1][0]| |arr[0][1]|
row 2 |arr[2][0]| |arr[0][1]|

Related

Is there a way to initialise array of integers with string?

Suppose that we have
int arr[3];
char str[20] = "{10,20,30}";
Is it possible to initialise arr with str?
You can't do that specifically, statically, but you can kind of do the reverse.
You can create a "to string" macro like this:
#define __STR(x) #x
#define STR(x) __STR(x)
Then you can use it like this:
#define NUMS {10,20,30}
int arr[3] = NUMS;
char str[] = STR(NUMS);
Not statically, you would need to parse the string and then assign the parsed values to arr.
You can parse numbers (and more) from strings with sscanf or with strtol (just parsing integers).
One way to parse {10,20,30} could be:
#include <stdio.h>
#include <string.h>
int main(void) {
int arr[3] = {0};
int pos = 0;
char str[20] = "{10,20,30}";
// str + 1: skip the first character '{'
char *token = strtok(str + 1, ",");
while (token) {
int tmp = 0;
// check if the parsing was actually successful
if (sscanf(token, "%d", &tmp) == 1) {
// a good program would check if 'pos' is within
// proper range of 'arr', in the case of arr[3]:
// acceptable range: 0-2
arr[pos] = tmp;
++pos;
}
// get the next token
token = strtok(NULL, ",");
}
for (int i = 0; i < sizeof(arr) / sizeof(* arr); ++i) {
printf("arr[%d] = %d\n", i, arr[i]);
}
}
This is very rudimentary it lacks proper handling of the {} braces and strtok IS NOT able to process more than one string at a time. A better solution would use strtok_r.

How do I print the assigned value of this letter instead of ascii number?

I want to print the assigned value of H = 2 by accessing the array. But when I access it from the array it gives me 72.
#include <ctype.h>
#include <stdio.h>
int main()
{
int H = 2;
char a[20] = "Hello";
printf("%d",a[0]);
}
assigning H=2 doesn't change its ascii value for you.
int H = 2;
H in the above statement is a variable.
char a[20] = "Hello";
While H in this one is a simple character in a string. Totally unrelated.
You can create your own print function that will print the way you need.
And you can create a LUT (look up table) that will store values that you want to print. Like this (not sure about syntax, just show the idea):
int ASCII_RANGE = 256;
int LUT[ASCII_RANGE];
int i = 0;
int H = 'H';
for (i = 0; i < ASCII_RANGE; ++i)
{
LUT[i] = i;
}
// here you define values that you want to print.
LUT[H] = 2;
And your printer:
void printer(int value)
{
printf("%d", LUT[value]);
}
The same way your printer can receive string and in loop to print all characters.
You can’t reassign character values. What you can do is create an array that’s indexed by the character value:
int map[256];
for ( int i = 0; i < 256; i++ ) // initialize the map array
map[i] = i; // so characters map to their
// default encoding
map['H'] = 2; // override the mapping for 'H'
char a[] = "Hello";
printf( "%d", map[a[0]] ); // print the value of map['H']

How to swap string in C?

I am trying to make a function in C which will swap two string variables but something went wrong and the program crashes.
Please have a look at my code and tell me where I made a mistake:
#include <string.h>
void strswap(char name1[], char name2[]) // to swap two strings
{
int lengthname1, lengthname2;
lengthname1 = strlen(name1);
lengthname2 = strlen(name2);
char temporaryname1[100];
char temporaryname2[100];
int x;
int y;
// till just the declaration
for (int x = 0; x < lengthname1; lengthname1++) {
temporaryname1[x] = name1[x];
name1[x] = ' ';
}
// copying the value of name1 in temporaryname1
for (int y = 0; y < lengthname2; lengthname2++) {
temporaryname2[x] = name2[x];
name2[x] = ' ';
}
// copying the value of name2 in temporaryname2
for (int x = 0; x < lengthname1; lengthname1++) {
name1[x] = temporaryname2[x];
}
for (int y = 0; y < lengthname2; lengthname2++) {
name2[x] = temporaryname1[x];
}
}
#include <stdio.h>
int main()
{
char name[] = "hello";
char name2[] = "hi";
printf("before swapping: %s %s\n", name, name2);
strswap(name, name2);
printf("after swapping: %s %s\n", name, name2);
}
EDIT:- I have corrected the program and it is working properly. Soon my header file is going to work with some other modules. Thank you all for your help and especially to #Micheal
There are many issues:
First issue
The x variable is not initialized:
int x; int y; // first declaration of x
// till just the declaration
for(int x=0;x<lengthname1;lengthname1++)
{// ^ second declaration of x , local to the loop
temporaryname1[x]=name1[x];
name1[x]=' ';
}
// if you use x here it's the first x that has never been initialized
Second issue
This:
for (x = 0; x<lengthname1; lengthname1++)
should be:
for (x = 0; x<lengthname1 + 1; x++)
Why lengthname1 + 1 ? Because you need to copy the NUL char that terminates the string.
There are similar problems in your other for loops as well.
For example here you use y as loop variable, but in the loop you use x:
for (int y = 0; y<lengthname2 + 1; lengthname2++)
{
name2[x] = temporaryname1[x];
Third issue
In main you declare this:
char name[] = "hello";
char name2[] = "hi";
That is actually the same as
char name[6] = "hello"; // 5 chars for "hello" + 1 char for the terminating NUL
char name2[3] = "hi"; // 2 chars for "hi" + 1 char for the terminating NUL
Now even if your strswap is correct, you are trying to stuff the 6 bytes from the name array ("hello") into the 3 bytes array name2, there is not enough space in the name2 array. This is undefined behaviour.
And last but not least:
This is simply useless:
name1[x] = ' ';
And finally
You should ask yourself why you need two temporary strings (temporaryname1 and temporaryname2) in strswap() - one is enough.
void strswap(char ** name1, char ** name2)
{
char * name1_1 = malloc(strlen(*name2) + 1);
char * name2_1 = malloc(strlen(*name1) + 1);
strncpy(name1_1, *name2, strlen(*name2) + 1);
strncpy(name2_1, *name1, strlen(*name1) + 1);
*name1 = name1_1;
*name2 = name2_1;
}
int main()
{
char * name="hello";
char * name2="hi";
printf("before swapping %s %s\n",name,name2);
strswap(&name, &name2);
printf("after swapping %s %s\n",name,name2);
return 0;
}
Actually following is the safest way to swap two strings. In your cases, you were statically using strings of size 100 in size, which is not good and work in all case. Moreover, You tried to use ' ' instead of '\0' to mark end of string. String APIs uses '\0' to indicate that string has ended.

How do I print all array elements on the same line?

I had to delete all the code. What I' looking is how to sprintf all elements of an array in the same line.
The display has 2 lines, I need to print the array 10,24,32,40,51, .....first line
and 10,51 .....second line
sample
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *join(int n, const int array[n], const char *format, const char *sep){
if(!format)
format = "%d";
if(!sep)
sep = ", ";
size_t len = strlen(sep)*(n-1)+1;//+1 for EOS
int i;
for(i=0;i<n;++i)
len += snprintf(NULL, 0, format, array[i]);
char *result = malloc(len);
if(!result)return NULL;
size_t pos = 0;
for(i=0;i<n;++i){
pos += sprintf(result + pos, format, array[i]);
if(i != n-1)
pos += sprintf(result + pos, "%s", sep);
}
return result;
}
int main (void){
int array[][5]={{10,24,32,40,51},{10,1,99,77,88}};
int row_size = sizeof(array)/sizeof(array[0]);
int col_size = sizeof(array[0])/sizeof(int);
char *join_str;
int i;
for(i=0;i<row_size;++i){
char *join_str = join(col_size, array[i], "%2d", ", ");
printf("%s\n", join_str);
free(join_str);
}
return 0;
}
Your array has 10 elements
#define N 10
int V[N] = {10,34, 34, 11};
However, it is partially explicitly initialised so that indices 0, 1, 2 and 3 contain 10, 34, 34 and 11 respectively. A partially explicitly initialised array in C will have the remaining elements (4 .. 9 inclusive) implicitly initialised to 0.
You then:
sprintf (str, "%d %d ... %d %d", V[0], V[1], V[N-2], V[N-1];
This isn't code you are actually running, as it is missing a ), and str is undefined. However, what this would do is write four values to str (not the screen), being values 0, 1, 8 and 9 (i.e. the first 2 and last 2 values), i.e. the characters 0 1 0 0 plus a terminating NULL.
As you are using sprintf() not snprintf() you have no way of checking whether this will overflow str.
It's difficult to tell what you are then doing because of the formatting of the question, but it appears you are calling a function array that might or might not modify the array and print it out again. However, your assembler function is defined as:
__asm void array (int V[], int N, int V) ....
which has an array / pointer parameter called V, a second parameter called N (though the main program #defines this to 10 (so that won't work), and a third parameter also called V which won't work as that's the name of the first parameter.
You also have a mysterious X defined to 10, which is then unused.
It's not particularly clear what you are asking and it would be better if you posted a small working code snippet, but I hope the above is of help.

C convert section of char array to double

I want to convert a section of a char array to a double. For example I have:
char in_string[] = "4014.84954";
Say I want to convert the first 40 to a double with value 40.0. My code so far:
#include <stdio.h>
#include <stdlib.h>
int main(int arg) {
char in_string[] = "4014.84954";
int i = 0;
for(i = 0; i <= sizeof(in_string); i++) {
printf("%c\n", in_string[i]);
printf("%f\n", atof(&in_string[i]));
}
}
In each loop atof it converts the char array from the starting pointer I supply all the way to the end of the array. The output is:
4
4014.849540
0
14.849540
1
14.849540
4
4.849540
.
0.849540
8
84954.000000 etc...
How can I convert just a portion of a char array to a double? This must by modular because my real input_string is much more complicated, but I will ensure that the char is a number 0-9.
The following should work assuming:
I will ensure that the char is a number 0-9.
double toDouble(const char* s, int start, int stop) {
unsigned long long int m = 1;
double ret = 0;
for (int i = stop; i >= start; i--) {
ret += (s[i] - '0') * m;
m *= 10;
}
return ret;
}
For example for the string 23487 the function will do this calculations:
ret = 0
ret += 7 * 1
ret += 8 * 10
ret += 4 * 100
ret += 3 * 1000
ret += 2 * 10000
ret = 23487
You can copy the desired amount of the string you want to another char array, null terminate it, and then convert it to a double. EG, if you want 2 digits, copy the 2 digits you want into a char array of length 3, ensuring the 3rd character is the null terminator.
Or if you don't want to make another char array, you can back up the (n+1)th char of the char array, replace it with a null terminator (ie 0x00), call atof, and then replace the null terminator with the backed up value. This will make atof stop parsing where you placed your null terminator.
Just use sscanf. Use the format "ld" and check for return value is one.
What about that, insert NULL at the right position and then revert it back to the original letter? This means you will manipulate the char array but you will revert it back to the original at the end.
You can create a function that will make the work in a temporary string (on the stack) and return the resulting double:
double atofn (char *src, int n) {
char tmp[50]; // big enough to fit any double
strncpy (tmp, src, n);
tmp[n] = 0;
return atof(tmp);
}
How much simpler could it get than sscanf?
#include <assert.h>
#include <stdio.h>
int main(void) {
double foo;
assert(sscanf("4014.84954", "%02lf", &foo) == 1);
printf("Processed the first two bytes of input and got: %lf\n", foo);
assert(sscanf("4014.84954" + 2, "%05lf", &foo) == 1);
printf("Processed the next five bytes of input and got: %lf\n", foo);
assert(sscanf("4014.84954" + 7, "%lf", &foo) == 1);
printf("Processed the rest of the input and got: %lf\n", foo);
return 0;
}

Resources