简体   繁体   English

如何从C中的函数返回的指针访问字符串

[英]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. 我有一个函数返回指向C中字符串的指针,并且正在尝试访问整个字符串,但不确定如何操作。

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. 我知道我可以放* pstring来获取字符串的第一个字符,但是我对如何获取其余字符有些迷茫。

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): 您可以使用以下格式说明符将字符串右填充为一定长度(例如: %-30s到右键盘, %-30s 30个字符):

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). 与其返回指向本地堆栈的指针,不如使用malloc分配内存,并记住在完成内存操作后将其free (或者由调用者传递在堆栈上分配的数组)。

You need to dynamically allocate name in padstring() if you wish to return that memory to the caller. 如果希望将该内存返回给调用者,则需要在padstring()动态分配name

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

First off, you need to null terminate your strings. 首先,您需要将字符串终止为null。 Second, you need to create the array on the heap using malloc (make sure to free the memory when you are done with it). 其次,您需要使用malloc在堆上创建数组(完成后确保释放内存)。

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. 只需使用sprintf()用空格填充字符串即可。

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");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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