Archived

This topic is now archived and is closed to further replies.

Metzler

Strange Problem with strncat

Recommended Posts

I got a strange problem with strncat. This is my code : [ CPP ] #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <cstring> void delete_space(char *text) { int i; int x = strlen(text); char temp[]=""; for (i = 0; i < x; i++) { if (text != 32) { strncat(temp, &text[i], 1); } } strcpy(text, temp); } void main() { char *active; char *active2; char name2[] = "Music_Path = d:\mp3"; char *token; active = strtok(name2, "="); delete_space(active); printf("\n%s, %d",active, strlen(active)); active = strtok(0, " "); delete_space(active); printf("\n%s, %d",active, strlen(active)); getch(); } [ /CPP ] The Problem is my delete_space(char *text) function. It should eliminate all spaces in a string, but it always terminates the for-loop after 4 runs, no matter which string i pass to the function. Could anybody help me ? Its really getting on my nuts... [edited by - Metzler on July 18, 2002 3:14:34 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Hi,
I think the problem is with char temp[]="";. When u r using strncpy, it assumes that the string has enough additional memory to hold the appended part. The program might work for a while till the routine accesses some invalid/protected location.

a better way would be to replace -
strncat(temp, &text, 1);

with -
strcpy(temp,temp+1);

and u do not need the stmt -
strcpy(text, temp);

at the end. But u might look for multiple space as well.

Share this post


Link to post
Share on other sites