null compare in C language [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 6 years ago.
Improve this question
i already have this code in C language, is a string of 15 data delimited by commas the code split the string by comma and store every data in a single variable called array[], the issue is that i have the last data comma if after the last comma there are no data then the variable x15 = 0, but if there are a value after the last , then convert that value to a int. i print the value of the array[15] to verify and this is null, so i out a condition for that but do not work, the program just break after compiling.
char buf[] ="¶bL0 L3,01,+08590323,-079343001,010215,00000000000000,-tN,000,012689997,001219456,000,7FF2,C07F,0,4,";
printf("\n \n string=[%s]\n\n", buf);
int i = 0;
int u;
char *p = strtok (buf, ",");
char *array[16];
char *y15;
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, ",");
}
for (i = 0; i <16; ++i){
if(array[15] == NULL){
wbt.x15=0;
}else{
wbt.x15=atoi(array[15]);
}
//printf("data: [%s]\n", array[i]);
}

You are using an uninitialized array element, which is cause for undefined behavior.
You have:
char *array[16];
The elements of the array are uninitialized. And then, you proceed to use:
if(array[15] == NULL){
wbt.x15=0;
}else{
wbt.x15=atoi(array[15]);
}
It's not clear why you have that check for every iteration of the loop but that's another problem. The problem with the posted code is that array[15] is not initialized. Using that value is a problem.
Make sure you initialize array properly. Use:
char *array[16] = {0};
Also, I think your for loop needs to be something like:
for (i = 0; i <16; ++i)
{
int x = 0;
if(array[i] != NULL)
{
x = atoi(array[i]);
}
// Now use x.
}

Related

string splitting logic in C programing [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 months ago.
Improve this question
Could you please provide me some code or solution how to split the below string in C programming
Sample string :
SMABCDEFGHIJK,887276617459,5,552612260849779,552612260840646,552612260843632,552612260843525,552612260846817
Output needed :
552612260849779,552612260840646,552612260843632,552612260843525,552612260846817
Basically for the input string we would need to Ignore first 3 positions and want rest of the string in different variable.
The positions to ignore and delimiter values will get the from the database table label.
So, If someone help me to give the logic that would be very helpful
In your case, you do not need to split the string. Simply ignore everything before the n-th occurrence of the delimiter.
char *ignoreFisrstN(const char *str, int delim, size_t ignoreCount)
{
char *result = NULL;
while(ignoreCount--)
{
if((str = strchr(str, delim))) str++;
else break;
}
if(str)
{
result = malloc(strlen(str) + 1);
if(result) strcpy(result, str);
}
return result;
}
int main(void)
{
char *s = "SMABCDEFGHIJK,887276617459,5,552612260849779,552612260840646,552612260843632,552612260843525,552612260846817";
for(size_t i = 0; i < 10; i++)
{
char *r = ignoreFisrstN(s, ',', i);
printf("%zu: `%s`\n", i, r ? r : "NULL");
free(r);
}
}
https://godbolt.org/z/xWe74sY46

How to replace a multi-character character constant with one character [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 3 years ago.
Improve this question
I'm attempting to replace '%7C' with a '|' in C but i'm getting a multi-character character constant warning. I was wondering if it was possible to do this and if so how? I was attempting using the code below but it gave this warning.
Parse.c
char *parse(char *command){
char * newCommand = (char *)malloc(sizeof(char)*35);
newCommand = strtok(command, " ");
newCommand = strtok(NULL, "/run?command= ");
for(int i = 0; i<strlen(newCommand); i++){
if(newCommand[i] == '+')
{
newCommand[i] = ' ';
}
if(newCommand[i] == '%7C')
{
newCommand[i] = '|';
}
}
return newCommand;
}
Multi-character constants are not portable and should generally be avoided. Your code comes under the 'general' category.
Part of the solution to your problem is to do a string comparison (with strncmp):
if (strncmp(&newCommand[i], "%7C", 3) == 0)
{
newCommand[i] = '|';
}
However, you also need to remove the 7C. That requires more surgery on the loop:
int tgt = 0;
int len = strlen(newCommand);
for (int src = 0; src < len; src++)
{
if (newCommand[src] == '+')
{
newCommand[tgt++] = ' ';
}
else if (strncmp(newCommand[i], "%7C", 3) == 0)
{
newCommand[tgt++] = '|';
src += 2;
}
else
newCommand[tgt++] = newCommand[src];
}
newCommand[tgt] = '\0';
This maintains two indexes into the newCommand array, one from which you're reading (src) and one to which you're writing (tgt — dst would be an alternative name). The src += 2; skips over the 7C after replacing % with |.
Uncompiled code!
Also, in your function you have:
char *newCommand = (char *)malloc(sizeof(char)*35);
newCommand = strtok(command, " ");
This immediately leaks the allocated memory. Maybe you need to use strdup() or:
char *newCommand = malloc(strlen(command) + 1);
if (newCommand == NULL) …report error and bail out…
strcpy(newCommand, command);
And the next line:
newCommand = strtok(NULL, "/run?command= ");
splits on any sequence of any of the characters in the constant string; it does not look for that string. If you want to look for the string, then you need strstr() instead, and you need to run strtok() first, perhaps, to get the right starting point (maybe newCommand = strtok(NULL, ""), then char *end = strstr(newCommand, "/run?command= "); — and check for null pointers returned.
With the revised allocation, you need a new symbol to record the pointers returned by strtok() — such as char *token;.
All in all, there's a lot of work needed on your code.

Array of of Struct containing array of char as members - C [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 4 years ago.
Improve this question
I have a struct like this:
struct vertices{
char x[20];
char y[20];
char z[20];
};
and then in main I have an array of the struct vertices like this:
struct vertices vert[64];
plus an array of char in my main function like this:
char exampleArray[200]="v 23.232000 32.33000 2.03900\nv 9.20900 3.29000 1.0002\n";
so what I want to do is to parse this big array containing a hundred or so vertices, and store each value in the corresponding x,y,z char arrays of the struct vertices, which later I'm gonna simply convert by calling on
float x=atof(vert[1].x) and draw each one.
But the problem is that I can't store , copy, concat characters from the raw array to the x,y,z arrays by any ways, i tried to do it by vert[0].x=exampleArray[0], vert[0].x=exampleArray+i etc inside different conditions like
if(SpaceCount==1)
{
vert[0].x[0]=exampleArray[i];
i++;
}
but all this doesn't work.
I tried so many variations, couldn't list them all.
But the thing I want is to parse the exampleArray which has my vertices in raw format, every 3D vertix has spaces in between them, every vertix starts with a char V followed by a space, the first point is the X then followed by a space and then the Y point and after the Z point there is newline \n character and then again a V for a new vertix.
You could use strtok() with delimiter " \n" to get each piece and then strcpy() to place each token in your struct.
struct vertices {
char x[20];
char y[20];
char z[20];
};
int main(void)
{
char exampleArray[200] = "v 23.232000 32.33000 2.03900\nv 9.20900 3.29000 1.0002";
char *toStrtokVertex, *token;
char delim[5] = " \n";
struct vertices V[10];
int i = 0;
toStrtokVertex = exampleArray;
while ((token = strtok(toStrtokVertex, delim)) != NULL) {
// ignore the `v`
// get x
if ((token = strtok(NULL, delim)) != NULL) {
strcpy(V[i].x, token);
}
else {
printf("INPUT ERROR\n");
exit(1);
}
// get y
if ((token = strtok(NULL, delim)) != NULL) {
strcpy(V[i].y, token);
}
else {
printf("INPUT ERROR\n");
exit(1);
}
// get z
if ((token = strtok(NULL, delim)) != NULL) {
strcpy(V[i].z, token);
}
else {
printf("INPUT ERROR\n");
exit(1);
}
// switch this to NULL to keep parsing the same string
toStrtokVertex = NULL;
i++;
}
for (int j = 0; j < i; j++) {
printf("V[%d] (%s, %s, %s)\n", j, V[j].x, V[j].y, V[j].z);
}
}
Note that I modified your input value to match your description. You had
"v 23.232000 32.33000 2.03900\n 9.20900 3.29000 1.0002"
which did not have a v after the \n to start the next vertex, so I added a v
"v 23.232000 32.33000 2.03900\nv 9.20900 3.29000 1.0002"
Character arrays are not copied by simply pointing at them. The function "strcpy(vert[0].x, &exampleArray[2])" is needed, but even then there is no '\0' immediately after that first number to indicate where to stop reading. "memcpy" does not need a NULL ('\0') but needs a length based on spaces.
Further, the "atof" operation to plan to use requires a NULL terminator as well.
I am concerned with your "space planning". You have 64 copies of structures that will each require 60 characters (3840 total), but your exampleArray only has 200. And the input string exampleArray has strings for numbers that must be no longer than 19 digits/decimals because you need the NULL terminator in each of x/y/z to exist.
This is the pure technical evaluation of code issues, but your original post does not show more of the application design. Help us understand your application design and more advice can be given.

Parsing string pointer in C - Troubleshoot [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am new to C
I am trying to parse the string by "spaces" and "commas", string that *ch pointing to, but I am getting the first element only. Not sure what I am doing wrong, and I have wasted my whole day already on this, but still couldn't figure out.
#include <stdio.h>
#include <string.h>
int main(){
char *ch = "This is a string, and fyunck you.";
char cmd[100], *temp;
int i = 0, size_ch = strlen(ch), count = 0;
/* as strtok only support string array */
for (i = 0; i < size_ch; i++){
if (ch[i] != ','){
cmd[count] = ch[i];
count++;
}
}
cmd[count] = '\0';
printf("cmd: %s\n", cmd);
ch = strtok(cmd, " ");
printf("ch: %s\n", ch);
while ( (ch = strtok(NULL, " ")) != NULL)
printf("%s\n", cmd);
}
Output
cmd: This is a string and fyunck you
ch: This
This
This
This
This
This
This
whereas, the output should be
Desire Output
cmd: This is a string and fyunck you
ch: This
is
a
string
and
fyunck
you
Note: I am not allowed to use external libraries.
P.S I am trying to replicate this code, Code
You're just printing the wrong variable in the last line.
Change
printf("%s\n", cmd);
to
printf("%s\n", ch);
and it should be fine.
Note this:
while ((ch = strtok(NULL, " ")) != NULL)
printf("%s\n", cmd);
You are updating ch, and outputting cmd, which remains unchanged.
To fix this, simply change it to:
while ((ch = strtok(NULL, " ")) != NULL)
printf("%s\n", ch);

Passing strings as pointer to a function [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 9 years ago.
Improve this question
It's a simple function for many but as a beginner, I've yet to overcome the pointer ghost specially when it comes to strings. I understand some of the examples of strcmp, strcpy, strlen as well as how the characters are assigned in the memory with a NULL terminator. I think I also get the point how a pointer variable in memory points to the address of a int var or char etc. and you assign them by dereferencing them to var/char, but whenever I try to write a code, the pointer ghost comes back to bite me.
So, here I'm trying to run this and doesn't work. I would appreciate if you could clarify this for me...
//GETNAME function should return a string that is not NULL and less than 20 characters
char getname (char *s1)
{
int i, n;
char s2[i];
printf ("Enter your name:" );
scanf ("%s", "s2");
if (s2 == NULL)
return 0;
else if(n<20)
for ( i=0, n =strlen (s2 + 1); i<n; i++)
*(s1+i) = s2[i]; //copy characters from s2 and point to chars of s1
return *s1;
}
int main (int argc, char *argv[])
{
char name[20];
char urname;
urname = getname(name);
printf (" Your name is : %s\n", urname);
getch();
return NULL;
}
Here are several errors; there may be more:
Uninitialized variable:
int i, n;
char s2[i];
i is not initialized here, yet you use it as if it was. What value should i have? Like this it is undefined behaviour.
Incorrect argument to scanf:
scanf ("%s", "s2");
The second parameter should be a pointer to the memory that you want the input to be written to, not a constant string. It should be:
scanf ("%s", s2);
Incorrect argument to strlen:
for ( i=0, n =strlen (s2 + 1); i<n; i++)
You want to add 1 to the string length not to the string itself, so it should be
for ( i=0, n = strlen(s2) + 1; i<n; i++)
General issues with getname, including return type:
char getname (char *s1)
Why is this function so complex? You could directly scanf into the parameter s1. You don't need s2 for anything. Also the return type is wrong. You return a pointer, not a single char. It should be:
char* getname(char *s1)
Not handling return value from getname properly:
char urname;
urname = getname(name);
getname returns a pointer to char, not a single char. It should be:
char* urname;
urname = getname(name);
As the previous post says that i is not initialised.
Also the line
scanf("%s", "s2");
Should be
scanf("%s", s2);
The lines
if (s2 == NULL)
return 0;
else if(n<20)
Is incorrect as s2 will not be NULL and n is not initialised
... That is for starters
I recommend you get a book and read it

Resources