Problem when using the strchr function.
Problem when using the strchr function.
The code below result in a null value despite the fact that a colon is in the string. This is incorrect ip_address = strchr(ip_address_string, ':'); The code below result in an 'r' value because the letter r is in the string. This is correct ip_address = strchr(ip_address_string, 'r'); =============================== root:/home# ./string_1 ip_address = (null) =============================== Code:
#include <stdio.h> |
I don't know...it works okay for me:
Code:
itsme:~/C$ cat strchr.c |
reply
Hi itsme86. Thank you for your help.
I used the function s = strtok(ip_address_string, ":") and then I used the function ip_address = strchr(ip_address_string, ':') and that is why it gives me a null value. The function strtok kept a hidden static pointer. When I called the strchr function afterward, the pointer points to null. If I commented out the code s = strtok(ip_address_string, ":") it gives a correct answer when I run the code ip_address = strchr(ip_address_string, ':') =================================== Code:
#include <stdio.h> |
Problem when using the strchr function.
I am having a similar problem with strchr with SUSE Linux 10.1. The following code compiles and works fine on MS-Dos and SCO Unix 5.06 but generates a Segmentation fault on SUSE Linux 10.1.
#include <stdio.h> #include <string.h> #include <stdlib.h> main() { static char buffer[80]; void converter(); fprintf(stdout,"Try entering 90-45-9\n"); fgets(buffer,79,stdin); converter(buffer); fprintf(stdout,"Try entering 90.775\n"); fgets(buffer,79,stdin); converter(buffer); return 0; } void converter(char *buffer) { char *p, *q; double d, e, f; d = atof(buffer); p = strchr(buffer,'-'); p++; if(*p == '-') { e = atof(p); q = strchr(p,'-'); if(*q == '-') { q++; f = atof(q); } } fprintf(stdout,"%f %f %f\n",d, e, f); } |
welcome to linux questions. in the future please use code tags as they preserve the formatting and make the code alot easier to read.
as for your segfault, it might have something to do with you asking for a . > fprintf(stdout,"Try entering 90.775\n"); and then looking for a - > strchr(buffer,'-'); then you continue through converter() without verifying that p is valid. if you were to add this block after p = strchr(buffer, '-'); in converter.. you should see where you are going wrong. Code:
if(!p) |
Problem when using the strchr function
Follow up on my earlier post:
Use p = strchr(buffer,'-'); if(p == NULL) NOT p = strchr(buffer,'-'); if(*p == NULL) |
Quote:
|
All times are GMT -5. The time now is 11:04 PM. |