LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 06-10-2020, 07:40 PM   #1
atharvdesai1996
LQ Newbie
 
Registered: Dec 2019
Posts: 12

Rep: Reputation: Disabled
Issue Returning string to char * return type function


In this code below to find longest common prefixes in strings, I am facing issue that in main function, the print statement is printing NULL instead of showing 'fl' which is returned through str1 as seen in the function. What can be the issue?



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * longestCommonPrefix(char ** strs, int strsSize);

int main()
{
char *str[3]={ "flower", "flight", "flow"};
char * final = NULL;
final =longestCommonPrefix(str, 3);
printf(" common chars are %s",final );
return 1;
}



char * longestCommonPrefix(char ** strs, int strsSize)
{
int i=0, j=0;
char *mystr;
char str1[10];
char chari;


for ( i=0; i<strlen(strs[0]); i++)
{
chari= *(strs[0]+i);
printf("Character to be compared is = %c\n",chari);
for (j=0;j<strsSize;j++ )
{
if (*(strs[j]+i)!=chari)
{
break;
}
if(j==strsSize-1)
{
str1[i]=chari;
str1[i+1]='\0';

printf(" Final cooman char = %c at %p \n", str1[i], str1 + i);
}


}


}
printf("\n ####### %s and address %p ",str1, &str1);

return str1;
}
 
Old 06-10-2020, 10:52 PM   #2
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 9,605

Rep: Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279Reputation: 4279
Code:
char * longestCommonPrefix(char ** strs, int strsSize)
{
char str1[10];

// snip

return str1;
}
This was flagged by the compiler when I tried to build it.

You allocate str1 on the stack and then you return its address.

It's no longer at that address after the function returns.
 
Old 06-11-2020, 12:26 AM   #3
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,056

Rep: Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469Reputation: 1469
It is enough to store/return the length of the prefix.
Note: you shouldn't call `strlen` in the cycle, it is a waste of CPU.
Code:
int i, j;
int found_string_terminator=0;

for (i=0; strs[0][i]!='\0' &&
          !found_string_terminator; ++i) {
...
}
 
1 members found this post helpful.
Old 06-11-2020, 08:08 AM   #4
GazL
LQ Guru
 
Registered: May 2008
Posts: 5,497
Blog Entries: 14

Rep: Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328Reputation: 3328
strs[0][i] - Ooh, elegant. I wouldn't have thought of that.

On the downside, it does make strs look like a two dimensional array, which could catch out those more familiar with higher-level languages. *( strs[0] + i ), while more verbose, is easier to grok, IMO.


I agree with Neve' about only returning a count rather than the string itself. The caller can then use that length value to create a new string if it needs too. Maybe something like this:

Code:
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

size_t longestCommonPrefixLength( char *strs[] )
{
    size_t common = 0;
    bool done = false;

    if ( ! strs || ! strs[0] )
        return 0;
    
    for ( size_t i = 0 ; ! done ; i++ )
    {
        for ( size_t j = 0 ; strs[j] && ! done ; j++ )
        {
            if ( *(strs[j] + i) == '\0' || *(strs[j] + i ) != *(strs[0] + i) )
                done = true;
        }
        if ( ! done )
            common++;
    }
    
    return common;
}

char *strndup( char *src, size_t n )
{
    char *str = malloc( n + 1 );
    if (str)
    {
        strncpy( str, src, n );
        str[n] = '\0';
    }

    return str;
}

int main()
{
    static char *strs[] = { "Flower", "Floor is a rock goddess!", "Flow", "Flew", NULL };

    for ( char **s = strs ; *s ; s++)
        puts(*s);
    
    char *const str = strndup(strs[0], longestCommonPrefixLength(strs));
    if (str)
    {
        printf("\ncommon prefix: %s\n", str);
        free(str);
    }
    
    return 0;
}
 
Old 06-11-2020, 10:08 AM   #5
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 305

Rep: Reputation: Disabled
A shorter version:

Code:
#include <stdio.h>

int longestCommonPrefix (char* strs[]) {

        int i = 0, j = 0;

        char* pstr0 = strs[0];

        while (pstr0 && *pstr0 == strs[i][j]) {
                ++i;

                if (!strs[i]) {
                        i = 0;
                        ++j;
                        ++pstr0;
                }


        }

        return (int) (pstr0 - strs[0]);
}

int main () {
        char *strs[] = { "Flower", "Floor is a rock goddess!", "Flow", "Flew", NULL };

        int len = longestCommonPrefix (strs);

        printf ("%u\n", len);

        char *strs2[] = { "Flower", "Floor is a rock goddess!", "Flow", NULL };

        len = longestCommonPrefix (strs2);

        printf ("%u\n", len);

        char *strs3[] = { "Chewing", "Chewed", "Chew", NULL };

        len = longestCommonPrefix (strs3);

        printf ("%u\n", len);

        return 0;
}
 
1 members found this post helpful.
Old 06-13-2020, 12:00 PM   #6
Contrapak
Member
 
Registered: May 2019
Location: /home/
Distribution: Arch Linux
Posts: 165

Rep: Reputation: 60
I'd love to help, OP, but your code is unreadable. Please, next time, use the [CODE] tag.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Returning char pointer from function which has array of char pointer srinietrx Programming 3 10-30-2015 03:55 AM
difference between char *string and char string[20] savio Programming 7 08-10-2015 01:51 AM
format '%s' expects type 'char *', but argument 3 has type 'char (*)[31]' RuijunFan Programming 7 11-13-2014 12:15 PM
[SOLVED] copy string a to string b and change string b with toupper() and count the chars beep3r Programming 3 10-22-2010 07:22 PM
c++ problem setting "const char *str" from function returning a string ocularb0b Programming 3 03-04-2008 09:36 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:31 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration