C字符串的malloc(输出) [英] C strings malloc (output)

查看:128
本文介绍了C字符串的malloc(输出)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些奇怪的输出在这里。你能解释我为什么和如何解决呢?

I have some strange output here. Could you explain me why and how to solve it?

int inp_str(char * string, char ** pointers[])
{
    char * tmp[stringsCount];
    if (strlen(string) > maxlen)
    return (-1);
    else {
    tmp[count] = malloc(sizeof(char) * strlen(string));
    strcpy(tmp[count], string);
    pointers[count] = &tmp[count];
    count++;
    }
    return count;

}


int main(){

    //char * strings[stringsCount];
    char ** pointers[stringsCount];
    inp_str( "sdasya", pointers);
    inp_str( "dasd", pointers);
    inp_str( "qwe", pointers);
    inp_str( "dasd", pointers);

    //sort(pointers, count);
    printf("%s", *pointers[0]);
    printf("\n%s", *pointers[1]);
    printf("\n%s", *pointers[2]);
    printf("\n%s", *pointers[3]);
}

下面是输出:

sdasya
��uNH��H�l$ H�\$L�d$(L�l$0H��8�f.�
qwe
�bs7

PS。 stringsCount是常数;数= 0

PS. stringsCount is constant; count = 0

推荐答案

由于的char * TMP [stringsCount]; 是一个局部变量,函数后 inp_str 的回报, TMP 被系统回收。所以指针到该位置是在函数返回之后失效。

Because char * tmp[stringsCount]; is a local variable, after the function inp_str returns, the memory of tmp is reclaimed by the system. So the pointers to that location are invalid after the function returns.

这篇关于C字符串的malloc(输出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆