简体   繁体   中英

How to access a string from a pointer returned by a function in C

I've a function returning a pointer to a string in C and I'm trying to access the entirety of the string but I'm not sure how to.

I've a function that loops threw a linked list of structs containing student data and gets the student's names. I want to pad spaces onto the ends of each string so they are all the same size. So I wrote a function for padding the strings. The function returns a pointer to the string but I don't know how to access the whole string from the pointer. I know I can put *pstring to get the first character of the string but I'm a little lost on how to get the rest.

This loops through the linked list:

void myFunction(void) {

    pStudent = pHead;
    char paddedName[30];
    long nameLength = 0 ;

    while(pStudent->pNext != NULL){
        printf("%c,\n", *padstring(pStudent->name));
        strcpy(paddedName, padstring(pStudent->name));
        nameLength = strlen(paddedName);
        printf("%lu | %s | %s \n", nameLength, paddedName, pStudent->name);
        pStudent = pStudent->pNext;
    }
    printf("\n");

}

This pads and returns the string:

char *padstring(char* string){

    char name[30];
    int i = 0;

    while(i < 30){
        if(i < strlen(string)){
            name[i] = string[i];
                    }
        else{
            name[i] = ' ';
        }
        i++;
    }
    printf("%s,\n", name);
    return name;

}

It's not necessary to create a new string. You can output a string right-padded to a certain length using the format specifier below (eg: %-30s to right-pad to 30 characters):

printf("[%-10s]", name);

/* [Name      ] */

If you do create a new string, you'd want to return a valid memory location. Rather than returning a pointer to the local stack, use malloc to allocate the memory and remember to free it when done with it (alternatively pass in an array allocated on the stack by the caller).

You need to dynamically allocate name in padstring() if you wish to return that memory to the caller.

char *name = malloc(30);
if (name == NULL) {
    return NULL;
}

First off, you need to null terminate your strings. Second, you need to create the array on the heap using malloc (make sure to free the memory when you are done with it).

I generally prefer to do the padding in the same string. Of course you have to make sure there is enough space which you can do by passing the maximum size. I pass the pad length to make it more flexible. It can be further improved by passing the character that you want to pad with in case it isn't always a space.

This is a quick example.

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

char* padstring(char *s, int maxlen, int padlen)
{
    int len = strlen(s);

    if (len < padlen)
    {
        char *p = s + len;
        while ((len < maxlen) && (len < padlen))
        {
            *p++ = ' '; // Add a space
            *p = 0;     // Null terminate
            len++;
        }
    }

    return s;
}

int main(int argc, char *argv[])
{
    char s[50] = "Hello";

    printf("'%s'\n", padstring(s, sizeof(s), 30));
    return 0;
}

There is no need to define a new function in your case. Just use sprintf() to fill string with spaces.

void myFunction(void) {

    // Declare max length of name
    const int MAX_LEN = 29;

    pStudent = pHead;
    char paddedName[MAX_LEN + 1];
    long nameLength = 0 ;

    while(pStudent->pNext != NULL){
        // Record origin length
        nameLength = strlen(pStudent->name);
        // Just write spaces after pStudent->name
        sprintf(pStudent->name + nameLength, "%-*s", MAX_LEN - nameLength, "");

        nameLength = strlen(pStudent->name);
        printf("%lu | %s | %s \n", nameLength, paddedName, pStudent->name);
        pStudent = pStudent->pNext;
    }
    printf("\n");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM