Insert string to double array [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I got help here a few days ago in the construction of a function that gets a string of the like:
"1 2.2 3 4.4 5 6.6 7 8.5"
and insert it to array[2][4] (in this case) in the following form:
1 | 3 | 5 | 7
2.2|4.4|6.6|8.5
the function that do that the array is:
//'function' is char*,'array' is double array
for(p = function; *p != '\0' ;p++){//convert double by strtod
item = strtod(p, &p);
++div;
if((div%2)!=0)
{
array[0][j]=item;
}
else
{
array[1][j++]=item;
div=0;
}
}
the problem in the code that the function insert the values only to array[0][j] and not to array[1][j] the meaning the array seems like(if the array initialized to 0 in the begin):
1 | 3 | 5 | 7
0 | 0 | 0 | 0
the values insert only to the first line of the array,
if i call to the function with string:
"0.5 2 1 4 3 6 0.5 8"
so item always be 0 and i don't know why :\
The previous post:
Try to insert string to array to check if the string describe function
thanks

Initially, your code works. But then your pointer, p, is being incremented past the end of the string and you are seeing whatever is in memory after that, and overwriting the contents of your array. The problem is here:
for(p = function; *p != '\0' ;p++) {
item = strtod(p, &p);
// (other code)
}
After calling strtod for the very last number (8.5), the pointer p already points to the NULL terminator. But then, your for loop calls p++ which increments it one past the NULL terminator. Your function continues running for some time after that, filling the array with garbage and possibly corrupting memory.
A solution is:
for(p = function; *p != '\0' ;) {
item = strtod(p, &p);
// (other code)
}
In this case, on most iterations, p points to the space before each number. That is okay, since strtod explicitly ignores whitespace. After the last iteration, p points to the NULL terminator and your loop ends before corrupting the array and possibly other parts of memory.
Dealing with pointers this way is error-prone. I’d recommend using the parsing facilities provided in the language, starting with strtok().

Related

What is the meaning of the 2 in calculating the length of a substring as "(right-left+2)"? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am designing a program in C to detect tokens.
I got confused in the 4th line. What does the (right-left+2) do?
char* sub_string(char* str, int left, int right)
{
int i;
char* sub_str = (char*) malloc(sizeof(char)*(right-left+2)); /* 4th line */
}
right-left+2 in this case would be right-left+1+1.
Where righ-left would be the length from left to right, but without counting the left one. Hence one +1.
The other +1 is for making one additional character of space, most likely for adding a 0 termination.
By the way, the function is missing a clean return statement.
E.g. (thanks David C. Ranking for the idea of an example) "this" within "more this than that":
more this than that
0 5 8
The 't' is at left 5, the 's' is at right 8. The length of "this" is clearly 4 (not counting the, absent, 0 terminator). But 8-5 is only 3. So use one +1 to include the additional character (by my counting the 't' is missing...).
If that substring is to be returned via a pointer to malloced memory, which is what I guess the (missing) rest of the function is supposed to do; it should include the 0-terminator in the malloced memory. That needs another character of memory to be malloced; by using the second +1.

How to explain the output of this program in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I've been working on this problem:
#include<stdio.h>
int main()
{
printf("%c", "abcdefgh"[4]);
return 0;
}
This gives e as the output, however I couldn't understand that how an array named "abcdefgh" with 4 elements is getting printed.
In nutshell, please tell me how this program works.
The string "abcdefgh" doesn't have 4 elements. It's an array with 9 elements (the characters plus the null terminator, and square brackets are the array subscript operator.
So "abcdefgh"[4] is getting the element at index 4 from "abcdefgh" which is 'e'.
In C, a string is sequence of character terminated by null character (\0).
When you declaring a string:
"abcdefgh"
it's actually:
char array[9] = "abcdefgh";
and you are accessing 5th character from the array, since array is 0-based data-structure.
you are actually doing:
printf("%c",array[4]);
therefore, it points to 5-th character in array;
a b c d e f g h
0 1 2 3 4 5 6 7
A string literal like "abcdefgh" is an array expression - its type is "9-element array of char" (8 characters plus the string terminator). The subscript operator works on it like any other array expression, so "abcdefgh"[4]" evaluates to the 5th element of the string, which is the character 'e'.

Reproduce values from an original array after substitution of each element with the mean value of its neighbours in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have substituted the values in an array with the values of the arithmetic mean of its neighbours in C:
int main(void) {
int tab[5] = {1,2,4,6,8};
for (int i = 1; i<4; i++) {
tab[i] = (tab[i-1]+tab[i+1])/2;
}
return 0;
}
I have excluded the first and the last element. Then, I want to reproduce the orginal values in the modified array. I have tried:
for (int i = 3; i>=1; i--) {
tab[i-1] = 2*tab[i] - tab[i+1];
}
but it doesn't work. How to reproduce the original values? I want to modify the original list in order to avoid the memory usage for initialization of the new array.
You can't do that IN THIS CASE.
Also there are hidden mistake in your code (explained at bottom)
look at the modified array in your case
arr[0] = 1 //unmodified in loop
arr[1] = 2 //(5/2 = 2) in int data type
arr[2] = 4 //(arr[1]+6)/2 = (2+6)/2 = 4
arr[3] = 6 //(arr[2]+8)/2 = (4+8)/2 = 6
arr[4] = 8 //unmodified
since, its a specific case where the modified array is same, so some of the mistakes would be hidden.
but what happens when your second loop has i=1
arr[i-1]=2*arr[i] - arr[i+1]
arr[0]=2*arr[1] - arr[2]
taking values from above
arr[0] = 0 // which is different from original arr[0]
If you want to just examine this use float instead of int as data type of array and see what happens.
also try putting an even value in the first element while using the int data type.
Now, the mistakes
you said you want to replace elements with avg of their neighbours. but (not in this special case where original elements are retained) what happens is the loop works correctly only 1st time and from 2nd run it is taking a value tab[i-1] which you modified in the previous loop run.
same is the case of your second de-modification loop, from 2nd run onwards, it takes a value tab[i+1] that you modified in previous run.
even if everything else works,
do you realize that in second loop, you are assigning original values from 2nd to 0th positions instead of their original 3rd to 1st.

Not understanding weird behaviours of printf() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I found a question asking for output of the following statement :
printf("%d"+1,123);
The answer given was d, It's explanation was : Since "%d" is a string, +1 here means d.
123 just gets ignored.
My first question is : why 123 gets ignored?
I also ran the following statement
printf("%d"+2,123);
It printed nothing. The code runs but without errors.
My second question is : why did the code compiled without errors?
Third time, I did following:
printf("%d"+0,123);
Output was 123.
So I am getting real confused here. If +1 printed d, then shouldn't +0 print %?
Imagine a string:
char str[] = "%d";
Now we know that:
str[0] == '%'
str[1] == 'd'
str[2] == '\0' = 0x00
str+2 == &str[2] == the address of the byte 0x00 inside the str string == ""
printf("%d", 123); is the same as printf(str, 123)
printf("%d" + 2, 123); if the same as printf("", 123); and it will print "", ie. nothing
A character point with an addition lead to a character point.
printf is just a function
So it takes a variety of parameter - varags
"%d"+1 Will be a string just dn it
"%d"+2 - will be the null byte - nothing
"%d"+0 - Will be %d - hence expected output - see the manual page
Answer to your first question:
123 gets ignored because while writing printf("%d"+1,123), +1 places the pointer at index 1 of %d i.e d. Since, to print 123 we need the pointer to be at % and access %d and not just d. Hence, only d gets printed out in this case.
Answer to your second question
It compiled without error because printf() is just a function and it takes various arguments. For more details about printf() you can visit this link
And in the third case i.e printf("%d"+0,123), the output is 123 because here the pointer's position is at 0 i.e at % and we have access to %d. Hence, we're getting 123 as output.
hope this will help you.

C - sscanf() %d picking up zero and causing destination &curritem.stock to be NULL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
sscanf() is great for the problem i'm facing, but it's doing something unexpected.
tmp is a line read in from a file, i need to parse out parts of the line into separate pieces of data. curritem is a struct with int dollar, int cent, cat[], int stock, and int history[].
The odd issue i'm having is that when %d picks up a double zero (00), it appropriately inserts integer zero into destination, but upon confronting a single zero (0), the integer is not added appropriately to the destination; for example, while collecting data pertaining to history[], all is well, adding 1, 4, 8, 2, 13, etc. to the array, but a single zero cuts everything off there, as if NULL terminated at that point, which i presume is related.
The code:
sscanf(tmp, "%d.%d%s %d %d %d", &curritem.dollar, &curritem.cent,
curritem.cat, &curritem.stock, &curritem.history[0],
&curritem.history[1]);
I have left out some indices of curritem.history[], as it clutters the necessary information.
Example of what i should get, if all integers were added correctly:
curritem.history[0...11] = 5 2 6 1 0 11 9 0 15 0 7 10
What actually results as of right now:
curritem.history[0...11] = 5 2 6 1
Something dies when sscanf() sees a single '0' via %d and adds that to &struct.intarray[n]
Any ideas?
Try not to recommend an entirely different solution to my general program function, sscanf() is working wonders in every other aspect.
Thank you for your time!
EDIT:
A snippet of exact input:
WL162343Fleece-Lined Double L Jeans 49.95PANTS 3 8 1 0 1 0 7 1 5 2 10 2 6
All information is acquired successfully until after the category- in this case, 'PANTS'.
With this example, my int array called history should hold the values
3 8 1 0 1 0 7 1 5 2 10 2 6
But upon printing every item in the array:
int n = 0;
for (n = 0; curritem.history[n]; n++) {
printf("%i ", curritem.history[n]);
}
The following output results:
3 8 1
EDIT:
The 'for' loop used for printing is incapable of distinguishing between an integer '0' and a null-termination of the array. Annoying.
What do you think that curritem.history[n] will return in the for's condition when it contains zero?

Resources