开发者

How to determine the amount of memory required by my char*?

I've this simple program and need to know on which basis should I choose the have for the variable (howToPredectThisNumber) (i.e. the size of the char* string).

And Which is best to choose in this case, char[] or char*??

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

typedef struct
{
    char* name;
}Emp;

void init(Emp** emp)
{
    int howToPredectThisNumber = 50;
    *emp = malloc(sizeof(Emp));
    (*emp)->name = NULL;
    (*emp)->name = calloc(howToPredectThisNumber, sizeof(char*));
}

void release(Emp** emp)
{
    free((*emp)->name);
    free(*emp);开发者_StackOverflow社区
}

void setName(Emp* emp, char* newName)
{
    strcpy(emp->name, newName);
}
char* getName(Emp* emp)
{
    return emp->name;
}

int main(void)
{
    Emp* emp;
    init(&emp);
    setName(emp, "Muhammad            Abdullah");
    printf("%s", getName(emp));
    release(&emp);

    return 0;
}


I guess you should delay that deduction until you know what you want to copy:

void setName(Emp* emp, char* newName)
{ 
    free(emp->name);
    emp->name = malloc( strlen( newName ) + 1 );
    strcpy(emp->name, newName);
}


I would use pointers less and use strdup instead of malloc+strlen+strcpy as thats what it is for.

A better solution is to realise that Emp isn't valid with a name and make sure its provided when created. If you forget to provide a name it won't compile instead of causing a segmentation fault when you run it.

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

typedef struct {
    char* name;
} Emp;

Emp *create(char * name) {
    Emp *emp = (Emp *) malloc(sizeof (Emp));
    emp->name = strdup(name);
    return emp;
}

void release(Emp* emp) {
    free(emp->name);
    free(emp);
}

void setName(Emp* emp, char* newName) {
    free(emp->name);
    emp->name = strdup(newName);
}

char* getName(Emp* emp) {
    return emp->name;
}

int main(int argc, char** argv) {
    Emp* emp = create("Muhammad            Abdullah");
    printf("%s", getName(emp));
    release(emp);

    return (EXIT_SUCCESS);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜