0
int string1()
{
char str[]="something"
}

int string2()
{
//here I need use array str[] from string1
}

how can I use array value? Im doing string operations

2
  • im not able to find one Commented Sep 28, 2017 at 1:26
  • It's kind of fundamental C stuff. You can't even begin to do C if you don't know how to pass parameters. You need to open a book and get the basics down before asking this kind of thing. int string2(char str[]) is the declaration and string2(str) is the invocation Commented Sep 28, 2017 at 1:28

4 Answers 4

3

Everyone has to learn how to use arrays, strings, pointers and functions -- and how to pass arrays and pointers to functions and handle function returns.

When you declare a variable (including an array type), the lifetime for the variable exists only within the scope it is declared unless memory for the variable is allocated dynamically or it is declared as static or otherwise has static storage duration.

Why? Storage for variables declared within a function is created on the function stack which is destroyed (released for reuse) on the function return. (main() is itself a function). Now a function can always return a value of its own type, but it cannot declare a an array of type with automatic storage within the function and return a pointer to the array.

char str[]="something";    /* violates that rule.... */

You have a few options, but they rely on understanding the storage duration for "something" and exactly what it is. let's look at what it appears you are attempting to do:

/* retuning pointer to string literal */
const char *string1 ()
{
    const char *s = "something";

    return s;
}

There are a few subtleties above. First "something" is a string literal and it has static storage duration for the life of the program. So you are assigning the address of "something" that is created in read-only memory that will survive the return of string1. Since a function can always return it's own type (in this case const char * -- chosen for that purpose), you can return the address to "something".

To use s in string2, you must pass s as an argument to string2, or assign the return of string1 to a global pointer (discouraged). Since s points to read-only memory, you should declare the parameter passed to string2 as const char * to signal it cannot be modified. Something similar to:

/* simply use string 's' in string2 */
void string2 (const char *s)
{
    printf ("in string2(), s : %s\n", s);
}

Putting it altogether, you could do something like the following:

#include <stdio.h>

/* retuning pointer to string literal */
const char *string1 ()
{
    const char *s = "something";

    return s;
}

/* simply use string 's' in string2 */
void string2 (const char *s)
{
    printf ("in string2(), s : %s\n", s);
}

int main (void) {

    /* call string 2 passing string1 as the parameter */
    string2 (string1 ());

    return 0;
}

Example Use/Output

$ ./bin/literalreturn
in string2(), s : something

note: you can only get away with returning s in string1 because of the string literal static storage duration. Otherwise, you would need to pass s as a parameter to string1 or dynamically allocate storage for s within string1 and return a pointer to the starting address for the new block of memory.

If you were passing a character array to string1, then you would need to do something similar to the following:

#include <stdio.h>
#include <string.h>

#define MAXC 32     /* constant for array size */

/* anytime you are passing an array, pass the size. */
char *string1 (char *s, size_t max)
{
    if (max < 2) {
        fprintf (stderr, "error: insufficient max size.\n");
        return NULL;
    }

    if (strlen (s) < max - 1)
        strcpy (s, "something");

    return s;
}

/* simply use string 's' */
void string2 (const char *s)
{
    printf ("in string2(), s : %s\n", s);
}

int main (void) {

    char buf[MAXC] = "";  /* declare character array of MAXC chars */

    /* call string 2 passing string1 passing array and size */
    string2 (string1 (buf, sizeof buf));

    return 0;
}

(Since s isn't changed in string2 it is still properly passed as const char *s which allows certain compiler optimizations for your code.)

Look things over. You must understand the subtleties of each example as these concepts underlie much of C. Let me know if you have further questions.

Sign up to request clarification or add additional context in comments.

9 Comments

I tried as per your answer its giving me - warning: passing 'const char *' to parameter of type 'char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
What compiler? I have gcc and cl.exe and do not get anything similar.
Your problem is pch = strtok (str,"."); strtok modifies str -- that is why you get the warning. Make a copy of str in modifiable memory and it will go away :) (note, that code is not in this question...)
can you tell me how to do that..i did but getting same error
char str[] = "your long string"; That creates str on the stack. It will be modifiable. Get rid of the const -- you want strtok to be able to chop the string up. Note the declaration from man strtok, e.g. char *strtok(char *str, const char *delim); You must always comply with the function declaration which is looking for char *, not const char * :)
|
1

You can use static variable in the function definition block, this has the global storage but limited access scope, when need to access it, just through the function call to get the pointer. Below is the code:

char* string1() {
    static char s[64] = "hello"; //this memory has 64 chars

    return s;
}


int main(int argc , char *argv[])
{
    char* s = string1();
    int len = strlen(s);

    printf("len: %d\n", len);

    for (int i = 0; i < len; ++i) {
        printf("char at: %d is %c\n", i, s[i]);
    }
}

Output:

len: 5
char at: 0 is h
char at: 1 is e
char at: 2 is l
char at: 3 is l
char at: 4 is o

5 Comments

instead of printing like this - printf("%s\n", string1()); I need to do some operation on say "s" as this variable we are passing, how to access "s"
Actually the printf call is one way of access "s", this is the why the content of s is get printed. In C, a string is internally a block of memory in which the content is stored. to access the block of memory, you just need the memory pointer to that memory, string1() returned that pointer.
i have tried this but its returning full function (string 1 function is executing two times )but I justt want values of s
for example: char* s = string1(); to read: char c = s[index], to write s[index] = c; make sure index is in the range of this block, which could be get by strlen(s)
still its returning the full function and not value
0

You can't. The string from the first function is a local variable and accessing it out of scope leads to undefined behavior. What you could do is allocate the string dynamically and hand control over it to the user.

Comments

0

If your str is a constant as in

char str[]="something";

it is a string literal you could simply return str which being an array, will decay into base address of the array because it would be in read only memory and will remain there till end of program. If this is the case the return type of the function should be char * like

char *string1();

See demo.

If the str is not so,

char str[30];
strcpy(str, "hello");

the str would be allocated in the stack and it cannot be accessed once control exits the function in which it is declared.

To circumvent this, you could allocate on heap memory like

char *string1()
{
    char *str=malloc(sizeof(char)*30);
    strcpy(str, "hello");
    return str;
}

And don't forget to deallocate the memory once you are done using it.

char *p=string1();
printf("\n%s", p);
free(p);

See demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.