0

hi everyone...
i"ve to pass a string as a returning value.but wat is the problem is there is an integer in the middle of it.the problem arise here..

char* my_string( char* dest,char *c)
{
     char str1[25] = "C:\\windows\\";
     char str2[25];
     char str3[25] = ".jpg ";
     strcat(dest,str1); //append str2 to str and return str
     strcat(dest,*str2);
     strcat(dest,str3);
     printf("%s",dest);
     return dest ;
}

i"m getting str2 value in main function.

My output should be C:\windows\1.jpg"

i dont know where to correct the program.waiting for a soon reply
thanks
cheran

Edited by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Aia
1

[...]
My output should be C:\windows\1.jpg"

i dont know where to correct the program.waiting for a soon reply
thanks
cheran

Start here:

char* my_string( char* dest,char *c)

There's not a need for another string if you are not using it.

strcat(dest,*str2);

Incorrect argument. str2 is the correct one. However that would not help you since str2 is not initialized to contain meaningful data. char str2[25];

My output should be C:\windows\1.jpg"

Then include that number. A possible solution.

char str2[] = "1";

Some other considerations.
The prototype of strcat goes something like this:

char * strcat ( char * destination, const char * source );

The first argument (char *destination) must be a "chunk" of memory that it can be modified. strcat(buffer, "My string"); where

char *buffer = "Meaningful string";

or

char *buffer; /* no memory allocated to it yet */

will not work.

char  buffer[25];
strcat(buffer, "My string");

Has the potential to work, however, there is a hidden caveat. Since buffer[25] is not initialized with meaningful data, it contains "unknown data or garbage". strcat will look for the '\0' in buffer so it knows where to start appending.
What happens if buffer[25]; contains #@%1'\0'2NoUse^[[[>fe7wp2Hne? Here's your function with possible corrections.

char *my_string( char *dest )
{
     char str1[] = "C:\\windows\\";
     char str2[] = "1";    /* this is '1', '\0' */
     char str3[] = ".jpg"; /* it is not the same than ".jpg " */
     
   /*
    *  strcat(dest, str1);
    *  if there is a meaningful string already in dest
    */

    /*
     * strcpy(dest, str1);
     * if dest is not initialized with a string already
     */
     
     strcat(dest, str2);
     strcat(dest, str3);

     return dest ;
}

Edited by Aia: n/a

Votes + Comments
i'm glad you took this. i just didn't have the energy.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.