[英]address not getting passed to a pointer from main to function. C
I am trying to read elements in a function and store them in an array in main. 我试图读取函数中的元素并将其存储在main中的数组中。 I use a pointer to a dynamic array, but its not working.
我使用了指向动态数组的指针,但是它不起作用。 The address i get when i deference the pointer is NULL and the program crashes.
当我引用指针时,我得到的地址为NULL,程序崩溃。
Here is the array : 这是数组:
char* first_name = malloc(first_name_length*sizeof(char));
Function call from main: 来自main的函数调用:
get_first_name(fp, first_name_length, first_name);
Function declaration: 函数声明:
void get_first_name(FILE* fp, int length,char* first);
Function definition: 功能定义:
void get_first_name(FILE* fp, int length, char* first){
char c;
int i = 0;
int number_of_conversions;
number_of_conversions = fscanf(fp, "%c", &c);
while (!isspace(c)){
first[i] = c;
number_of_conversions = fscanf(fp, "%c", &c);
i++;
}
}
something like the following will do the job 像下面这样的事情会做的
void get_first_name(FILE* fp, int length, char* first)
{
int c;
int i = 0;
while ( EOF != (c = fgetc(fp) ) && (' ' != c) && (i < (length -1)) )
{
first[i] = c;
i++;
}
// terminate the string
first[i] = '\0';
}
fp = fopen ( "file.txt", "r"));
fp = fopen(“ file.txt”,“ r”)));
Make sure file is not Empty. 确保文件不为空。 using fgetc() will help keeping it simple.
使用fgetc()将有助于保持简单。
void get_first_name(FILE* fp, int length, char* first) void get_first_name(FILE * fp,int length,char * first)
{ {
char c; 字符c;
int i = 0; int i = 0;
c=fgetc(fp); c = fgetc(fp);
while (c!=EOF && !isspace(c) ){ 而(c!= EOF &&!isspace(c)){
first[i] = c; first [i] = c;
c=fgetc(fp); c = fgetc(fp);
i++; i ++;
}} }}
3 . 3。 If you are using fscanf() for some purpose , you can use fseek() for checking if the file is Empty or not.
如果出于某些目的使用fscanf(),则可以使用fseek()检查文件是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.