[英]Dynamic matrix 2D array malloc() from external function allocation
[英]Array of dynamic string: allocation in external function
我需要你的幫助。
我有N個元素的靜態數組。 我需要使用一個函數插入動態分配的字符串。
這是我的代碼,有問題:
<<警告:從不兼容的指針類型傳遞“插入”的參數1。 預期為'char ***',但參數的類型為'char *(*)[N]'>>
謝謝你的幫助!
/* MAIN */
int main()
{
char* array[N];
int i=0;
while (...)
{
i++;
insert(&array, i);
}
...
free(array);
return 0;
}
/* FUNCTION */
void insert(char*** arrayPTR, int i)
{
printf("Enter the string: ");
scanf("%s", string);
(*arrayPTR)[i]=malloc( strlen(string) * sizeof(char) );
strcpy(*arrayPTR[i], string);
}
你快到了。 您的兩個主要問題是:
在將數組傳遞給函數時,您將添加一個額外的間接層,這是不必要的,實際上會導致問題。
盡管您需要free()
各個數組元素,但您也不需要-也不應該free()
數組本身,因為您沒有動態分配它。
這是應該更接近的內容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 5
#define MAX_BUFFER 100
void insert(char** arrayPTR, int i);
int main()
{
char* array[N];
/* Populate arrays */
for ( size_t i = 0; i < N; ++i ) {
insert(array, i);
}
/* Print and free them */
for ( size_t i = 0; i < N; ++i ) {
printf("String %zu: %s\n", i + 1, array[i]);
free(array[i]);
}
return 0;
}
void insert(char** arrayPTR, int i)
{
/* Prompt for and get input */
printf("Enter the string: ");
fflush(stdout);
char str[MAX_BUFFER];
fgets(str, MAX_BUFFER, stdin);
/* Remove trailing newline, if present */
const size_t sl = strlen(str);
if ( str[sl - 1] == '\n' ) {
str[sl - 1] = 0;
}
/* Allocate memory and copy */
if ( !(arrayPTR[i] = malloc(strlen(str) + 1)) ) {
perror("couldn't allocate memory");
exit(EXIT_FAILURE);
}
strcpy(arrayPTR[i], str);
}
輸出:
paul@thoth:~/src/sandbox$ ./dp
Enter the string: these
Enter the string: are
Enter the string: some
Enter the string: simple
Enter the string: words
String 1: these
String 2: are
String 3: some
String 4: simple
String 5: words
paul@thoth:~/src/sandbox$
樣品
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
void insert(char *arrayPTR[N], int index);
int main(void){
char *array[N] = { NULL };
int i, n;
for(i = 0; i<N; ++i){
insert(array, i);
if(*array[i] == '\0')
break;
}
n = i;
for(i=0; i < n; ++i){
puts(array[i]);
free(array[i]);
}
return 0;
}
void insert(char *arrayPTR[N], int i){
int ch, count = 0;
char *string = malloc(1);
printf("Enter the string: ");
while(EOF!=(ch=getchar()) && ch != '\n'){
string = realloc(string, count + 2);//Size expansion
string[count++] = ch;
}
string[count] = '\0';
arrayPTR[i] = string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.