C将静态char数组传递给函数

时间:2017-04-14 23:03:33

标签: c

我正在尝试将静态字符数组从标头传递给函数。问题是它在microseq.c中为第一个for循环获取了垃圾字符串 如何在microseq.c中正确使用静态字符串? 我在这个实验中使用了Xcode(8.3.1)。

的main.c

#include <stdio.h>
#include "main.h"
#include "microseq.h"

int main(int argc, const char * argv[]) {

    printf("Program starts here \n");
    microseq_t *microseq0;
    microseq0=load_microseq(*init_seq);

    free(microseq0);
    return 0;
}

main.h

#ifndef main_h
#define main_h
#include <stdlib.h>

static char* init_seq[13] = {
    "000011000004",
    "0FF000200004",
    "240C00FE0C04",
    "3D0000001041",
    "000000001F0D",
    "00000241240C",
    "8000004DC124",
    "040001FD1E14",
    "00000003AD33",
    "04000FF00004",
    "232AAA2FFFFC",
    "00FFFFFFFFFF"
};

typedef struct microseq {
    char* algo; 
} microseq_t;

#endif /* main_h */

microseq.c

#include "microseq.h"

microseq_t *load_microseq(char* algo) {
   microseq_t *ptr;

    ptr = (microseq_t*) malloc(sizeof(microseq_t));
    if(!ptr) {
        return ptr;
    }

    int i;

    ptr->algo = algo;
    printf("function starts here\n");
    for (i=0; '\0' != *(ptr->algo+13*i); i++) {
        printf("From top: %s    \n", ptr->algo+13*i);
    }
/*
It's printing garbage strings in between
"From top: Program starts here 

From top: s here "
*/
    for (i=0; *(init_seq+i)!=NULL; i++) {
        printf("Directly from: %s   \n", *(init_seq+i));
    }

    return ptr;
}

microseq.h

#ifndef microseq_h
#define microseq_h
#include "main.h"
#include <stdio.h>

microseq_t *load_microseq(char* algo);

#endif /* microseq_h */

输出:

Program starts here 
function starts here
From top: 000011000004    
From top: 0FF000200004    
From top: 240C00FE0C04    
From top: 3D0000001041    
From top: 000000001F0D    
From top: 00000241240C    
From top: 8000004DC124    
From top: 040001FD1E14    
From top: 00000003AD33    
From top: 04000FF00004    
From top: 232AAA2FFFFC    
From top: 00FFFFFFFFFF    
From top: Program starts here 

From top: s here 

Directly from: 000011000004   
Directly from: 0FF000200004   
Directly from: 240C00FE0C04   
Directly from: 3D0000001041   
Directly from: 000000001F0D   
Directly from: 00000241240C   
Directly from: 8000004DC124   
Directly from: 040001FD1E14   
Directly from: 00000003AD33   
Directly from: 04000FF00004   
Directly from: 232AAA2FFFFC   
Directly from: 00FFFFFFFFFF   
Program ended with exit code: 0

0 个答案:

没有答案