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.
Related
i have try this code made by me but no output and there's no errors?
#include <stdio.h>
void reverse(char *p,char *v,int size){
for(int i=size-1,j=0;i<0;i--){
*(v+j) = *(p+i);
j++;
}
}
int main(){
char word[6] = {"hello"};
char re_word[6];
re_word[5]='\0';
reverse(word,re_word,6);
printf("%s",re_word);
}
Using pointers it can look like this:
void reverse(char *w, char *revw, int slen) {
revw += slen - 1; // forward to pos. of last letter
revw[1] = '\0'; // one further *(revw+1)
while (*w)
*revw-- = *w++;
}
This is clear and symmetric, once it works, while your i-- and j++ are far apart.
slen is meant to be the number of letters w/o termination. Here the call:
char word[] = {"hello"};
char re_word[sizeof word];
reverse(word, re_word, sizeof word - 1);
strlen() should be used, probably, but these lines show how you can and have to control not just the total size but especially the last byte of the char array.
Without the correct length, reverse() would have to do a strlen() first, because it has to know how far away to put the first letter.
This *(v+j) = *(p+i) is more or less v[j] = p[i] and does not really take advantage of pointers, on the contrary.
(revw
caller) in reverse()
| |
v v
-4 -3 -2 -1 revw +1
o l l e h \0
... revw-- revw[1]
So revw is maybe not the best name inside the function; revw_first_backwards is meant...or fill_start. But before I fill backwards I do the one additional write to the right side to terminate the string: array notation using a pointer: revw[1] = '\0'.
First of all, i < 0 will always be false, given i = size - 1 > 0.
What you want is i >= 0.
Also, given size = 6, size - 1 will be equal to 5, and that is the NULL terminator position since array indexing in C start from 0. Perhaps use a C function such as strlen() to calculate the length rather than hard coding it.
void reverse(char *p, char *v, size_t size)
{
for (int i = size - 1, j = 0; i >= 0; i--)
{
*(v + j) = *(p + i);
j++;
}
}
int main()
{
char word[6] = {"hello"};
char re_word[6];
re_word[5] = '\0';
reverse(word, re_word, 5); /* or reverse(word, re_word, strlen(word)) */
printf("%s", re_word);
}
I got a homework question. I'm so close to complete program. I'm having trouble about one thing. This is the question:
Write a C program that generates and displays a character array of size 10 consisting of
random English lower-case letters. The program then asks the user how many times the array
will be right-shifted and displays the right shifted array at each right-shifting step. A sample
program execution output is given below. ( Hint: Use the ASCII codes of the English lower-case
letters which are 97, 98, ... 122 for a, b, ..., z, respectively, to generate the character array).
This is my code:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
void print_string (char *string){
int i;
for (i=0 ; i < 10 ; i ++){
printf("%c ", string[i]);
if (i == 9)
printf("\n");
}
}
void random_string(char *string, unsigned length)
{
/* Seed number for rand() */
srand((unsigned int) time(0) + getpid());
/* ASCII characters 97 to 122 */
int i;
for (i = 0; i < length; ++i)
{
string[i] = (rand() % 26)+ 97;
}
string[i] = '\0';
}
void reverse_string(char* str, int left, int right) {
char* p1 = str + left;
char* p2 = str + right;
while (p1 < p2) {
char temp = *p1;
*p1 = *p2;
*p2 = temp;
p1++;
p2--;
}
}
void rotate(char* str, int k, int n) {
reverse_string(str, 0, n-1);
reverse_string(str, 0, k-1);
reverse_string(str, k, n-1);
}
int main(void)
{
char s[11];
int i,shiftNum;
random_string(s, 11);
printf("Randomly constructed array is :\n");
print_string(s);
printf("Enter how many times array will be shifted: ");
scanf("%d",&shiftNum);
rotate(s,shiftNum,11);
print_string(s);
}
What's wrong with this code? When I execute it with 1, I couldn't get the first reverse correctly and I want to display all shifting steps.
For a start, it is atrocious that your lecturer/professor is telling you to use 97..122. C does not require that ASCII be the character set on every system, so this code is entirely non-portable, yet if you look at the history as far as Unix is concerned C is supposed to be a portable programming language. If you want to write this in a portable way, you need to store the characters in an array and select from that array:
char lowercase[] = "abcdefghijklmnopqrstuvwxyz";
string[i] = lowercase[rand() % (sizeof lowercase - 1)];
Now that we've covered that pedantic detail, Cool Guy indicated in a comment that this line of code is erroneous: string[i] = '\0';. He's correct about that.
This should also performed within main, not within random_string: srand((unsigned int) time(0) + getpid());. The reason is that calling random_string multiple times in the same second would result in the same "random string", which is very uncool.
scanf("%d",&shiftNum); can't guarantee success (that the user will input numeric data), and so can't guarantee that shiftNum will contain a sane value. You need to check the return value. For example:
if (scanf("%d", &shiftNum) != 1) {
puts("Invalid shift count!\n");
exit(0);
}
You should probably also consider using an unsigned type for shiftNum (and this will cause the corresponding format spec %d to change to something else, such as %u for unsigned int).
One more important task before I finish this task: You need to modify rotate to handle an input of 0 correctly, since some users might want to rotate/shift 0 times (as an alternative to not rotating/shifting at all). I'm confident that this should be an easy task for you.
Problem in C programming
I have following list:
int a[] = {0,0,1,0,0,1,0,2}
How do i convert following list items to char variable b?
Like this:
printf(%c, b)
OUTPUT: 00100102
I need this for printing the values of list in embedded system lcd screen where normal print options aren't available. Couldn't find similar example from www.stackoverflow.com. Vice versa there were many solutions to convert a string into a list.
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[] = {0,0,1,0,0,1,0,2};
const char *table = "0123456789";
size_t size = sizeof(a)/sizeof(*a);
char *b = malloc(size+1);
int i;
for(i=0;i<size;++i)
b[i]=table[a[i]];
b[i]='\0';
printf("%s\n", b);
free(b);
return 0;
}
int a = [0,0,1,0,0,1,0,2]
That is not valid C. Perhaps you meant:
const int a[] = { 0, 0, 1, 0, 0, 1, 0, 2 };
Converting a decimal digit to a printable character in C is easy, just add '0':
printf("%c", '0' + a[0]);
will print 0.
You can iterate through the elements of your array, and printf() each one, considering it as an offset from '0':
/*
'0' + 0 = '0'
'0' + 1 = '1'
'0' + 2 = '2'
*/
const int a[] = {0,0,1,0,0,1,0,2};
const int count = sizeof(a) / sizeof(a[0]);
int i;
for (i = 0; i < count; i++) {
printf("%c", '0' + a[i]);
}
printf("\n");
When you convert each value in an array of int to a corresponding value in an array of char, you just have an array of char. When you append the null terminator \0 (or 0) to the array of char, it becomes a C string.
int a[] = {0,0,1,0,0,1,0,2}; //use curly braces to assign values to new array.
char b[sizeof(a)/sizeof(a[0])+1];//Accomodates any size of a. note extra space for terminating \0
int i;
//EDIT 5 following lines
b[0]=0; //ensure string is null terminated
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
sprintf(b, "%s%d", b, a[i]);//copy one char per loop to concatenate string with all elements of `a`
}
Now you have a string, sized according to number of array elements in a that looks like:
"00100102"
In memory you would see |48|48|49|48|48|49|48|50|0|
(the integer values of each character representation of the integers 0, 1, & 2, with the null character 0 in the last position to mark the end of string.)
Note also, the phrase sizeof(array)/sizeof(array[0]) is used to get the number of elements in an array.
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]|
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;
}