简体   繁体   English

读字符串不起作用

[英]Reading strings doesn't work

I have this little code and I really can't figure out why it always gives me SIGSEGVs. 我有这么小的代码,我真的不知道为什么它总是给我SIGSEGV。

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

int read_strs(char **a, int *len) {

  int i;
  scanf("%d", len);
  if(*len <= 0) return 1;
  a = (char **) malloc(sizeof(char*) * (*len));
  if(a == NULL) return 1;
  for( i = 0; i < *len; i++ ) 
  {
      a[i] = malloc(sizeof(char) * 1000);
      scanf("%s", a[i]);
  }

  return 0;

}


int main(void) {
  int i, n;
  char **array;

  read_strs(array, &n);
  for( i = 0; i < n; i++ ) 
    printf("%s\n", array[i]);
    return 0;
}

It seems it doesn't even alloc the memory. 似乎它甚至没有分配内存。

The problem is that char ** array; 问题是char ** array; in your main function never gets loaded with the char ** array you malloc in test. 在主函数中,永远不会加载您在测试中分配的char **数组。 You send a copy of the pointer to read_strs - it won't get updated when you assign to it here: 您将指针的副本发送到read_strs-在此处分配指针时不会更新:

// a is local to test_str
a = (char **) malloc(sizeof(char*) * (*len));

You would need to pass a pointer to your char ** array variable if you want it to work in your current scheme. 如果希望它在当前方案中运行,则需要将指针传递给char ** array变量。 You could also simply return a from read_strs . 您也可以从read_strs返回a

edit : note, if you pass a pointer to char ** array , you'll also have to do work to make read_strs operate on a pointer to a char ** , whereas now it's operating on a simple char ** . 编辑 :请注意,如果将指针传递给char ** array ,则还必须做一些工作,以使read_strs在指向char **的指针上进行操作,而现在它在简单的char **上进行操作。

You need a couple fixes, but basically Walter is right 您需要进行一些修复,但是基本上Walter是正确的

 int read_strs(char***ax, *len){

then 然后

char **a;
a = *ax = (char**) malloc(sizeof(char*) * (*len));

then in the call, pass the location of array so that it can be filled by the function: 然后在调用中,传递array的位置,以便可以由函数填充:

read_strs(&array, &n);

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

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